简体   繁体   English

如何在C#中检查对象的某些属性是否为空

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

I have a class 我上课了

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

I work out the target of class A and populate the class with user input. 我计算出A类的目标,并用用户输入填充该类。 Each different target will mean different properties of the class are required(not empty/null). 每个不同的目标都意味着需要不同类的属性(不是空/ null)。

So if my target is banana, then propA and propB must not be empty. 因此,如果我的目标是香蕉,那么propA和propB不能为空。 If apple, then propB and propC must not be empty. 如果是apple,那么propB和propC一定不能为空。 I need to do this at the start of the application as to not keep doing checks in a later stage, as some methods and DB calls will require data etc. 我需要在应用程序启动时执行此操作,以便在后续阶段不再进行检查,因为某些方法和数据库调用将需要数据等。

What's the best way to code this? 编码的最佳方法是什么? or even design-wise. 甚至是设计明智的。 Is it good practice to store what properties are required for each target in an enum? 在枚举中存储每个目标所需的属性是一种好的做法吗? And then use what lazyberezovsky provided below to go through and check?? 然后使用下面提供的lazyberezovsky来检查?

The above example only has 3 properties, but what I'm actually required to do has heaps more. 上面的例子只有3个属性,但我实际需要做的事情还有更多。

I only just started looking at ways to validate my code. 我刚刚开始研究验证代码的方法。

In summary, there are two parts to this question. 总之,这个问题有两个部分。 - How to check whether a property of a class is empty - Storing a lists of different combined required properties somewhere to use against how to check - 如何检查类的属性是否为空 - 在某处存储不同组合所需属性的列表以用于检查如何检查

EDIT: sorry! 编辑:抱歉! I've edited to hopefully make more sense out of this. 我编辑过,希望能更好地理解这一点。

Let me try to guess what question was about :) 让我试着猜猜是什么问题:)

Here is type validator, which can check existence of parameter's public properties: 这是类型验证器,它可以检查参数的公共属性是否存在:

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;
    }
}

Usage with your class: 与您的班级一起使用:

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

Or you can use it as extension method public static bool IsPropertyExists<T>(this T t, string propertyName) with any object or generic parameter. 或者您可以将它用作扩展方法public static bool IsPropertyExists<T>(this T t, string propertyName)与任何对象或泛型参数。 But for me reflection is evil :) Try to resolve this issue by design. 但对我来说反思是邪恶的:)尝试通过设计解决这个问题。

I think what you are after is model validation. 我认为你所追求的是模型验证。 If so, perhaps a good place to put your validation logic is in a method of Class A, like this: 如果是这样,也许放置验证逻辑的好地方是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;
   }
}

How to check is propA is empty? 如何检查propA是空的? Depends on what propA is... is it an int? 取决于propA是什么......它是一个int吗? a bool? 一个博尔? a string? 一个字符串? etc... assuming it's a int than you can use the method above... 等...假设它是一个int而不是你可以使用上面的方法...

Can't think of a more "generic" validation than IsValid(), that is, I can't think of a more generic way to validate without knowing more... 想不出比IsValid()更“通用”的验证,也就是说,我想不出更通用的方法来验证而不知道更多...

I guess you mean validation when you say a property exists. 我猜你的意思是当你说房产存在时的验证。

You haven't specified if its an Web or Win Form/Wpf application (or whatelse). 您尚未指定其Web或Win Form / Wpf应用程序(或whatelse)。

You could implement IDataErrorInfo on you Classes and validate if properties have been filled right. 您可以在类上实现IDataErrorInfo并验证属性是否已正确填充。

There are tons of examples to find when Googling on IDataErrorInfo + Validate but here are some which helped me in the past: 在使用IDataErrorInfo + Validate进行Google搜索时,有大量示例可供查找,但以下是一些帮助我的例子:

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

How to validate child objects by implementing IDataErrorInfo on parent class 如何通过在父类上实现IDataErrorInfo来验证子对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM