如何以递归方式更改T的类型来触发Generic Class方法?

mer*_*lin 5 c# asp.net generics system.reflection

我创建了一个通用类来将一些数据解析成另一个类(MyClass1)的实例.由于MyClass1只有内置的C#类型,我的GenericMethod工作正常.当MyClass1有另一个MyClass2属性时问题开始增长,我仍然想调用我GenericMethod来解析我的数据.

我无法在其范围内触发我的Generic Class方法,因为我需要更改其类型T.有什么方法可以解决这个问题吗?

public class MyClass1 
{
    public int MyIntProperty { get; set; }
    public string MyStringProperty { get; set; }

    public MyClass2 MyClass2Property { get; set; }
}

public class MyClass2 
{
    public int MyOtherIntProperty { get; set; }
    public string MyOtherStringProperty { get; set; }
    public bool MyOtherBoolProperty { get; set; }
}

public class MyGenericClass<T> where T : class
{
    public static T MyGenericMethod()
    {
        T o = (T)Activator.CreateInstance(typeof(T));
        PropertyInfo[] pi = typeof(T).GetProperties();

        for(int i = 0; i < pi.Count(); i++) 
        {
            if(pi[i].Name == "MyClass2Property") 
            {
                //How to proceed ?
                MyGenericClass<???>.MyGenericMethod(); 
            }
            else 
            {
                pi[i].SetValue(o, Convert.ChangeType(someValue, pi[i].PropertyType), null);
            }
        }
    }
}        

public static void Main(string[] args) 
{
    MyClass1 mc1 = MyGenericClass<MyClass1>.MyGenericMethod();
    //Do something with mc1
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*B42 5

你可以看一下这篇文章

也许尝试这样的事情

public static class MyGenericClass<T> where T : class
{
    public static T MyGenericMethod()
    {
    T o = (T)Activator.CreateInstance(typeof(T));
    PropertyInfo[] pi = typeof(T).GetProperties();

    for(int i = 0; i < pi.Count(); i++) 
    {
        if(pi[i].Name == "MyClass2Property") 
        {
            //How to proceed ?
            Type t = typeof (MyGenericClass<>);
            Type genericType = t.MakeGenericType(new System.Type[] { pi[i].PropertyType });
            var c = Activator.CreateInstance(genericType);
            dynamic mgm = Convert.ChangeType(c, genericType);
            mgm.MyGenericMethod(); 
        }
        else 
        {
            pi[i].SetValue(o, Convert.ChangeType(someValue, pi[i].PropertyType), null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 而且,如果您不想基于属性名称进行切换(因为这会变得非常冗长乏味),您可以使用自定义属性来装饰您想要区别对待的属性. (2认同)