2016-12-02 42 views
0
public class MyModel 
    { 
     [Required] 
     public string Name { get; set; } 

     public AddressModel Address { get; set; } 

     ... 
    } 

是否有可能以某种方式检查是否AddressModel是一个新的类?如果是新的类,我需要做一些检查...C#检查,如果属性与属性新类里

通过新的类我的意思是

public class AddressModel { 

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


... 
} 

所以不只是对象,但也有如果里面的属性...

+4

请您约新类多一点解释? –

+0

你的意思是说它之前一直存在吗?如果是这种情况,则从持久性存储区传递该id,如果它等于默认值,则它不存在于存储区中,否则会存在。 – Igor

+0

'typeof(MyModel).GetProperty(“Address”,/ *绑定标志实例* /)。PropertyType'这将返回属性的类型,您可以检查属性值是默认还是somthing。 –

回答

0

我会尽力回答这个问题的一部分:(其余的我也不清楚)

所以不只是对象,但也有如果里面的属性...

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

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

这也有可能使用类的一个实例:

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

在这种情况下,可能是'MyModel myModel = new MyModel(); if(myModel.Address!= null){/ *对myModel.Address.GetType()* /}执行反射,但这需要OP的清晰度,因为这个问题没有意义。 – ColinM

+0

@ColinM你是对的,我限制了我的答案范围 –

0

你的问题是很模糊即使同时测试我们应该特别。关注细节。例如。想象一下班

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();