.NET reflection - Get Declaring class type from instance property

前端 未结 1 1648
臣服心动
臣服心动 2021-01-21 02:27

Is it possible to get the type of a class from a property instance

I tried the following

var model = new MyModel(\"SomeValueForMyProperty\")

Type declar         


        
1条回答
  •  执笔经年
    2021-01-21 02:59

    There is no direct link from a Type to a class declaring a property of that type.

    You'll need to use a PropertyInfo:

    PropertyInfo propInfo = model.GetType().GetProperty("MyProperty");
    
    // get the property value:
    object value = propInfo.GetValue(model, null);
    // get the property's declaring type:
    Type declaringType = propInfo.DeclaringType;
    

    0 讨论(0)
提交回复
热议问题