繁体   English   中英

字符串值的通用类型

[英]Generic type from string value

我有一个自定义类,它依赖于传递类型T来传递。 我只知道字符串形式是什么类型,因为它是如何被发送的。 我一直在寻找,但似乎无法找到我需要的确切内容。 我可以将字符串值解析为类型,但我需要将其解析为...某些东西,我可以作为泛型参数传递。


我已经改写了我的问题,因此:

// Classes structure
namespace Mynamespace
{
    public interface IRequest
    {
    }

    public interface IHandler<T> where T : IRequest
    {
        void Handle(T item);
    }

    public class MyRequest : IRequest
    {
    }

    public class MyHandler : IHandler<MyRequest>
    {
        void Handle(MyRequest item)
        {
        }
    }
}

// The info I get, and I know typeString is a IRequest
string typeString = "My";
object requestItem = [insert xml parsing here];

// I then create a handler, to handle the request
Type typeHandler = Type.GetType("Mynamespace." + typeString + "Handler");
var handler = Activator.CreateInstance(typeHandler);

Type typeRequest = Type.GetType("Mynamespace." + typeString + "Request");

// what I want to do:
handler.Handle(requestItem);

我不能这样做因为handler和requestItem只是对象所以我需要将'handler'解析为'typeHandler',并将requestItem解析为'typeRequest'

编辑:我想通了,我用InvokeMember来访问它。 :)

typeHandler.InvokeMember("Handle", BindingFlags.InvokeMethod, null, handler, new[] { requestItem });

你需要Type.MakeGenericType

Type typeArgument = Type.GetType(string.Format("Mynamespace.{0}", typeString));
Type template = typeof(MyClass<>);

Type genericType = template.MakeGenericType(typeArgument);

object instance = Activator.CreateInstance(genericType);

请注意,您无法将其MyClass<T>转换为特定的MyClass<T>因为您不知道T - 但它将在执行时成为正确类的实例。

Type closedType = typeof(MyClass<>).MakeGenericType(myGeneric);
object obj = Activator.CreateInstance(closedType);

请注意,除非您有非泛型接口或基类型,否则与这种类型的对象交谈非常棘手(除非您使用dynamic作弊)。 例如,非通用接口可能会有所帮助:

var obj = (ISomeInterface)Activator.CreateInstance(closedType);
obj.SomeMethodOnTheNonGenericInterface();

我想通了,我用InvokeMember来访问它。 :)

typeHandler.InvokeMember("Handle", BindingFlags.InvokeMethod, null, handler, new[] { requestItem });

暂无
暂无

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

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