Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

c# - Generic type from string value

I got a custom class, who relies on a generic type T to be passed along. I only know what type it is in string form, because that's how it's being sent. I've been searching around but can't seem to find exactly what I need. I can parse the string value to a type, but I need to parse it to... something, that I can pass as a generic parameter.


I've rewritten my problem, as such:

// 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);

I can't do that because handler and requestItem are just objects So I need to parse 'handler' to 'typeHandler', and requestItem to 'typeRequest'

Edit: I figured it out, I used InvokeMember to access it. :)

typeHandler.InvokeMember("Handle", BindingFlags.InvokeMethod, null, handler, new[] { requestItem });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need 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);

Note that you can't cast this to a particular MyClass<T> because you don't know T - but it will be an instance of the right class at execution time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...