简体   繁体   English

具有PropertyInfo.PropertyType类型的通用类实例

[英]Generic class instance with type from PropertyInfo.PropertyType

I have classes like below: 我有以下课程:

public class SampleClassToTest<T>
{
    public static Fake<T> SomeMethod(string parameter)
    {
        // some code
    }

    public static Fake<T> SomeMethod(string parameter, int anotherParameter)
    {
        //some another code
    }
}

public class Fake<T>
{
    // some code
}

And I want to use them in this way: 我想以这种方式使用它们:

SampleClassToTest<MyClass>.SomeMethod("some parameter");

The problem which I have is the following: type of "MyClass" I can get only from PropertyInfo instance using Reflection, so I have 我遇到的问题如下:“MyClass”的类型我只能使用Reflection从PropertyInfo实例获取,所以我有

Type propertyType = propertyInfo.PropertyType;

How can I do this? 我怎样才能做到这一点? Any ideas? 有任何想法吗?

UPD. UPD。 I'm trying to pass the Type to generic method. 我正在尝试将Type传递给泛型方法。 And yes, this is what I want. 是的,这就是我想要的。

You would need to do: 你需要这样做:

typeof(SampleClassToTest<>).MakeGenericType(propertyType)
       .GetMethod("SomeMethod", new Type[] {typeof(string)})
       .Invoke(null, new object[] {"some parameter"});

Ugly. 丑陋。

If it can at all be helped, I would advise offering a non-generic API that accepts a Type instance; 如果它可以在任何得到帮助,我会建议提供一个接受非通用API Type实例; the nice thing here is that a generic API can call into a non-generic API trivially by using typeof(T) . 这里的好处是通用API可以通过使用typeof(T)轻松调用非泛型API。

It looks like you want: 它看起来像你想要的:

Type propertyType;
Type classType = typeof(SampleClassToTest<>).MakeGenericType(propertyType);

MethodInfo method = classType.GetMethod("SomeMethod", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null);
object fake = method.Invoke(null, new object[] { "some parameter" });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM