How to access generic property without knowing the closed generic type

前端 未结 4 576
半阙折子戏
半阙折子戏 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 08:36

    You need to know the closed type of a generic class before you can access its generic members. The use of TestGeneric<> gives you the open type definition, which cannot be invoked without specifying the generic arguments.

    The simplest way for you to get the value of the property is to reflect on the closed type in use directly:

    public static void Main()
    {
        object myObject = new TestGeneric<string>("test"); // or from another source
    
        var type = myObject.GetType();
    
        if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), type))
        {
            var dataProperty = type.GetProperty("Data");
            object data = dataProperty.GetValue(myObject, new object[] { });
        }
    }
    
    0 讨论(0)
  • 2020-12-31 08:46

    Ahh, sorry for that. It was a simple mistake, the generic version works, of course it must read

    var dataProperty = myObject.GetType().GetProperty("Data");
    object data = dataProperty.GetValue(myObject, new object[] { });
    
    0 讨论(0)
  • 2020-12-31 08:55

    Oh, stackies... why didn't somebody point me to the dynamic type?? That's the perfect usage example which makes the code A LOT more readable:

    dynamic dynObject = myObject;
    object data = dynObject.Data;
    
    0 讨论(0)
  • 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<string>("test"); // or from another source
    
        var type = myObject.GetType();
    
        if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), type))
        {
            var dataProperty = type.GetProperty(nameof(TestGeneric<object>.Data));
            object data = dataProperty.GetValue(myObject);
        }
    }
    

    Notice that replacing type.GetProperty("Data") with type.GetProperty(nameof(TestGeneric<object>.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.

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