How to access generic property without knowing the closed generic type

前端 未结 4 575
半阙折子戏
半阙折子戏 2020-12-31 08:17

I have a generic Type as follows

public class TestGeneric
{
    public T Data { get; set; }
    public TestGeneric(T data)
    {
        this.Data =         


        
4条回答
  •  时光说笑
    2020-12-31 09:02

    With C# 6 and up we can use nameof to improve slightly Paul's answer:

    public static void Main()
    {
        object myObject = new TestGeneric("test"); // or from another source
    
        var type = myObject.GetType();
    
        if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), type))
        {
            var dataProperty = type.GetProperty(nameof(TestGeneric.Data));
            object data = dataProperty.GetValue(myObject);
        }
    }
    
    
    

    Notice that replacing type.GetProperty("Data") with type.GetProperty(nameof(TestGeneric.Data)) gives you compile time safety (so arguably better than using the dynamic way as well).

    Also using object as a type parameter is just a way to get access to the property and doesn't have any side effect or particular meaning.

    提交回复
    热议问题