C#检查属性是否为包含属性的新类

时间:2016-12-02 11:28:42

标签: c#

public class MyModel
    {
        [Required]
        public string Name { get; set; }

        public AddressModel Address { get; set; }

        ...
    }

是否有可能以某种方式检查AddressModel是否是新类?如果是新课,我需要做一些检查......

新课程我的意思是

 public class AddressModel {

[Required]
public string Street{ get; set; }


...
}

所以不仅仅是对象,而且如果内部有属性......

2 个答案:

答案 0 :(得分:0)

我会尽力回答这一部分:(其余部分对我来说不清楚)

  

所以不仅仅是对象,而且如果内部有属性......

您可以使用反射检查类型是否具有属性:

 Console.WriteLine(typeof(AddressModel).GetProperties().Count());

这也可以使用该类的实例:

AddressModel model = new AddressModel();
Console.WriteLine(model.GetType().GetProperties().Count());

答案 1 :(得分:0)

你的问题非常含糊,即使测试我们应该是esp。关注细节。例如。想象类

 public abstract class WeirdModel {
   // It's not me who implement this readonly property 
   protected abstract String Something {get;}
 }

 public class EerieModel {
   // write-only banned property  
   [Obsolete("Do not call obsolete properties!", true)]
   public string DoNotCallMe(set {...})
 }

 public class PrivateModel {
   // That's for me only
   private string PersonalInfo {get; set;} 
 } 

 public class StaticModel {
   // One property for all instances
   public static string CommonInfo {get; set;} 
 } 

你认为这些课程是新的吗?在任何情况下,您都必须获取属性,过滤掉它们,最后检查是否存在任何这样的属性:

 var isNew = typeof(AddressModel)
   .GetProperties(BindingFlags.Instance | BindingFlags.Public)
   .Where(property => property.CanRead && property.CanWrite)
   .Where(property => property.GetAccessors().All(method => !method.IsAbstract))      
    //TODO: put more conditions on properties if you want
   ...
   .Any();