簡體   English   中英

如何在C#中檢查對象的某些屬性是否為空

[英]How to check if certain properties of an object are not empty in C#

我上課了

class A {
    propA { get; set; }
    propB { get; set; }
    propC { get; set; }
    target { get; set; }
}

我計算出A類的目標,並用用戶輸入填充該類。 每個不同的目標都意味着需要不同類的屬性(不是空/ null)。

因此,如果我的目標是香蕉,那么propA和propB不能為空。 如果是apple,那么propB和propC一定不能為空。 我需要在應用程序啟動時執行此操作,以便在后續階段不再進行檢查,因為某些方法和數據庫調用將需要數據等。

編碼的最佳方法是什么? 甚至是設計明智的。 在枚舉中存儲每個目標所需的屬性是一種好的做法嗎? 然后使用下面提供的lazyberezovsky來檢查?

上面的例子只有3個屬性,但我實際需要做的事情還有更多。

我剛剛開始研究驗證代碼的方法。

總之,這個問題有兩個部分。 - 如何檢查類的屬性是否為空 - 在某處存儲不同組合所需屬性的列表以用於檢查如何檢查

編輯:抱歉! 我編輯過,希望能更好地理解這一點。

讓我試着猜猜是什么問題:)

這是類型驗證器,它可以檢查參數的公共屬性是否存在:

public class TypeValidator<T>
{
    public bool IsPropertyExists(string propertyName)
    {
        Type type = typeof(T);
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
        foreach (PropertyInfo property in type.GetProperties(flags))
            if (property.Name == propertyName)
                return true;

        return false;
    }
}

與您的班級一起使用:

TypeValidator<a> validator = new TypeValidator<a>();
validator.IsPropertyExists("PropB")

或者您可以將它用作擴展方法public static bool IsPropertyExists<T>(this T t, string propertyName)與任何對象或泛型參數。 但對我來說反思是邪惡的:)嘗試通過設計解決這個問題。

我認為你所追求的是模型驗證。 如果是這樣,也許放置驗證邏輯的好地方是A類方法,如下所示:

Class A
{
   Nullable<int> propA { get; set; }
   int? propB { get; set; }
   int? propC { get; set; }
   string target { 
      get { return _target; } 
      set { 
         var oldtarget = _target;
         _target = value; 
         if !IsValid() 
         {
             _target = oldtarget;
             throw new Exception("Setting target to " 
                        + value 
                        + " is not possible, ....");
         }
      } 
   }

   public bool IsValid()
   {
       switch (_target)
       {
           case "banana":
              return propA.HasValue() && propB.HasValue();

           case "apple":
              return propB.HasValue() && propC.HasValue();
       }

       return true;
   }
}

如何檢查propA是空的? 取決於propA是什么......它是一個int嗎? 一個博爾? 一個字符串? 等...假設它是一個int而不是你可以使用上面的方法...

想不出比IsValid()更“通用”的驗證,也就是說,我想不出更通用的方法來驗證而不知道更多...

我猜你的意思是當你說房產存在時的驗證。

您尚未指定其Web或Win Form / Wpf應用程序(或whatelse)。

您可以在類上實現IDataErrorInfo並驗證屬性是否已正確填充。

在使用IDataErrorInfo + Validate進行Google搜索時,有大量示例可供查找,但以下是一些幫助我的例子:

http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/

如何通過在父類上實現IDataErrorInfo來驗證子對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM