How to access generic property without knowing the closed generic type

前端 未结 4 609
半阙折子戏
半阙折子戏 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("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[] { });
        }
    }
    

提交回复
热议问题