本文介绍了逻辑和条件运算符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用逻辑/条件运算符无法确定正确的实现.我对应用程序有一个非常具体的要求,我以为一开始它可以正常工作,但是当放置在Marketplace上时,我发现我的实现根本无法正常工作.

I am having trouble figuring out the proper implementation using logical/conditional operators. I have a very specific requirement for an application and I thought at first it was working correctly, but when placed on the Marketplace I come to find out my implementation is not working at all.

  1. 如果我的应用程序处于试用模式,并且已保存的事件计数> 100,则我需要执行一项操作.
  2. 如果该应用程序处于试用"模式并且保存的事件计数是< = 100,或者该应用程序处于完整模式",那么我需要执行另一项操作.

在按钮单击事件中,我拥有的内容如下

What I have is as follows in a button click event

//recorded count of number of saved button presses
Settings.SavedCount.Value += 1;
        //both conditions must be true for the code to execute inside the 'if'
        if (TrialViewModel.LicenseModeString ==  "Trial" && Settings.SavedCount.Value > 100)
        {
            MessageBoxResult result = MessageBox.Show("You have saved over 100 items! Would you like to continue?", "Congratulations", MessageBoxButton.OKCancel);
            switch (result)
            {
                case MessageBoxResult.OK:
                    // A command takes a parameter and in this case we can pass null.
                    TrialViewModel.BuyCommand.Execute(null);
                    break;
                case MessageBoxResult.Cancel:
                    return;
                    break;
            }
        }
        //either the entire first condition OR the second condition must be true to execute the method ApplyAndSaveAsync()
        else if((TrialViewModel.LicenseModeString == "Trial" && Settings.SavedCount.Value <= 100) || TrialViewModel.LicenseModeString == "Full")
        {
            ApplyAndSaveAsync();
        }

在调试时,一切似乎都可以正常工作,尽管当我以试用和完整模式从市场上下载了该应用程序后,都没有执行ApplyAndSaveAsync()的情况.请注意,计数将始终无限期增加,但是应用程序可能会或可能不会处于试用模式.只有作为试用版下载并且在用户更新之前,它才处于试用"模式,在这种情况下,其许可证将自动更改为完全"模式.

when debugging everything seemed to work fine, although when I tested the application once it was downloaded from the marketplace in both trial and full modes, in neither case did ApplyAndSaveAsync() execute. To note, the count will always increase indefinitely but the application may or may not be in Trial mode. It is only in Trial mode if it is downloaded as a trial and before a user updates it, in which case its license will automatically change to Full mode.

编辑**

可能使用序数字符串比较而不是

string _license = TrialViewModel.LicenseModeString;
string _isTrial = "Trial";

// Use the overload of the Equals method that specifies a StringComparison.
// Ordinal is the fastest way to compare two strings.
bool result = _license.Equals(_isTrial, StringComparison.Ordinal);

Settings.SavedCount.Value += 1;
//both conditions must be true for the code to execute inside the 'if'
    if (result && Settings.SavedCount.Value > 100)
    {
        MessageBoxResult result = MessageBox.Show("You have saved over 100 items! Would you like to continue?", "Congratulations", MessageBoxButton.OKCancel);
        switch (result)
        {
            case MessageBoxResult.OK:
                // A command takes a parameter and in this case we can pass null.
                TrialViewModel.BuyCommand.Execute(null);
                break;
            case MessageBoxResult.Cancel:
                return;
                break;
        }
    }
    //either the entire first condition OR the second condition must be true to execute the method ApplyAndSaveAsync()
    else if((result && Settings.SavedCount.Value <= 100) || TrialViewModel.LicenseModeString == "Full")
    {
        ApplyAndSaveAsync();
    }

此外,使用逻辑和条件AND与OR函数之间的区别是什么?我想确保对ifif else语句中的两个语句都进行评估,以确保执行正确的过程.我的实现对此是否正确?

Also, what would be the difference between using logical and conditional AND and OR functions? I want to be sure that both statements in the if and if else statements are evaluated to ensure proper procedure. Is my implementation correct for this?

编辑2 **添加视图模型和类帮助程序以进行试用

Edit 2** Addition of View Model and Class helper for Trial Implementation

TrialViewModel

TrialViewModel

#region fields
private RelayCommand buyCommand;
#endregion fields

#region constructors
public TrialViewModel()
{
    // Subscribe to the helper class's static LicenseChanged event so that we can re-query its LicenseMode property when it changes.
    TrialExperienceHelper.LicenseChanged += TrialExperienceHelper_LicenseChanged;
}
#endregion constructors

#region properties
/// <summary>
/// You can bind the Command property of a Button to BuyCommand. When the Button is clicked, BuyCommand will be
/// invoked. The Button will be enabled as long as BuyCommand can execute.
/// </summary>
public RelayCommand BuyCommand
{
    get
    {
        if (this.buyCommand == null)
        {
            // The RelayCommand is constructed with two parameters - the action to perform on invocation,
            // and the condition under which the command can execute. It's important to call RaiseCanExecuteChanged
            // on a command whenever its can-execute condition might have changed. Here, we do that in the TrialExperienceHelper_LicenseChanged
            // event handler.
            this.buyCommand = new RelayCommand(
                param => TrialExperienceHelper.Buy(),
                param => TrialExperienceHelper.LicenseMode == TrialExperienceHelper.LicenseModes.Trial);
        }
        return this.buyCommand;
    }
}

public string LicenseModeString
{
    get
    {
        return TrialExperienceHelper.LicenseMode.ToString()/* + ' ' + AppResources.ModeString*/;
    }
}
#endregion properties

#region event handlers
// Handle TrialExperienceHelper's LicenseChanged event by raising property changed notifications on the
// properties and commands that
internal void TrialExperienceHelper_LicenseChanged()
{
    this.RaisePropertyChanged("LicenseModeString");
    this.BuyCommand.RaiseCanExecuteChanged();
}
#endregion event handlers

TrialExperienceHelper.cs

TrialExperienceHelper.cs

#region enums
    /// <summary>
    /// The LicenseModes enumeration describes the mode of a license.
    /// </summary>
    public enum LicenseModes
    {
        Full,
        MissingOrRevoked,
        Trial
    }
    #endregion enums

    #region fields
#if DEBUG
    // Determines how a debug build behaves on launch. This field is set to LicenseModes.Full after simulating a purchase.
    // Calling the Buy method (or navigating away from the app and back) will simulate a purchase.
    internal static LicenseModes simulatedLicMode = LicenseModes.Trial;
#endif // DEBUG
    private static bool isActiveCache;
    private static bool isTrialCache;
    #endregion fields

    #region constructors
    // The static constructor effectively initializes the cache of the state of the license when the app is launched. It also attaches
    // a handler so that we can refresh the cache whenever the license has (potentially) changed.
    static TrialExperienceHelper()
    {
        TrialExperienceHelper.RefreshCache();
        PhoneApplicationService.Current.Activated += (object sender, ActivatedEventArgs e) => TrialExperienceHelper.
#if DEBUG
            // In debug configuration, when the user returns to the application we will simulate a purchase.
OnSimulatedPurchase();
#else // DEBUG
            // In release configuration, when the user returns to the application we will refresh the cache.
RefreshCache();
#endif // DEBUG
    }
    #endregion constructors

    #region properties
    /// <summary>
    /// The LicenseMode property combines the active and trial states of the license into a single
    /// enumerated value. In debug configuration, the simulated value is returned. In release configuration,
    /// if the license is active then it is either trial or full. If the license is not active then
    /// it is either missing or revoked.
    /// </summary>
    public static LicenseModes LicenseMode
    {
        get
        {
#if DEBUG
            return simulatedLicMode;
#else // DEBUG
            if (TrialExperienceHelper.isActiveCache)
            {
                return TrialExperienceHelper.isTrialCache ? LicenseModes.Trial : LicenseModes.Full;
            }
            else // License is inactive.
            {
                return LicenseModes.MissingOrRevoked;
            }
#endif // DEBUG
        }
    }

    /// <summary>
    /// The IsFull property provides a convenient way of checking whether the license is full or not.
    /// </summary>
    public static bool IsFull
    {
        get
        {
            return (TrialExperienceHelper.LicenseMode == LicenseModes.Full);
        }
    }
    #endregion properties

    #region methods
    /// <summary>
    /// The Buy method can be called when the license state is trial. the user is given the opportunity
    /// to buy the app after which, in all configurations, the Activated event is raised, which we handle.
    /// </summary>
    public static void Buy()
    {
        MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
        marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;
        marketplaceDetailTask.Show();
    }

    /// <summary>
    /// This method can be called at any time to refresh the values stored in the cache. We re-query the application object
    /// for the current state of the license and cache the fresh values. We also raise the LicenseChanged event.
    /// </summary>
    public static void RefreshCache()
    {
        TrialExperienceHelper.isActiveCache = CurrentApp.LicenseInformation.IsActive;
        TrialExperienceHelper.isTrialCache = CurrentApp.LicenseInformation.IsTrial;
        TrialExperienceHelper.RaiseLicenseChanged();
    }

    private static void RaiseLicenseChanged()
    {
        if (TrialExperienceHelper.LicenseChanged != null)
        {
            TrialExperienceHelper.LicenseChanged();
        }
    }

#if DEBUG
    private static void OnSimulatedPurchase()
    {
        TrialExperienceHelper.simulatedLicMode = LicenseModes.Full;
        TrialExperienceHelper.RaiseLicenseChanged();
    }
#endif // DEBUG
    #endregion methods

    #region events
    /// <summary>
    /// The static LicenseChanged event is raised whenever the value of the LicenseMode property has (potentially) changed.
    /// </summary>
    public static event LicenseChangedEventHandler LicenseChanged;
    #endregion events

推荐答案

这可能是在黑暗中显示,但在某些情况下(在Java中为somtimes,但我不确定.NET),使用"== "不起作用.您可以尝试使用比较"方法代替"==.

This may be a show in the dark, but in some cases (somtimes in Java, but I am not sure about .NET) string comparison with "==" does not work. You could try using the "compare" method instead of "==".

这篇关于逻辑和条件运算符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!