Pass An Instantiated System.Type as a Type Parameter for a Generic Class

后端 未结 6 1176
萌比男神i
萌比男神i 2020-11-21 07:46

The title is kind of obscure. What I want to know is if this is possible:

string typeName = ;
Type myType = Type.GetType(         


        
6条回答
  •  臣服心动
    2020-11-21 08:02

    Some additional how to run with scissors code. Suppose you have a class similar to

    public class Encoder() {
    public void Markdown(IEnumerable contents) { do magic }
    public void Markdown(IEnumerable contents) { do magic2 }
    }
    

    Suppose at runtime you have a FooContent

    If you were able to bind at compile time you would want

    var fooContents = new List(fooContent)
    new Encoder().Markdown(fooContents)
    

    However you cannot do this at runtime. To do this at runtime you would do along the lines of:

    var listType = typeof(List<>).MakeGenericType(myType);
    var dynamicList = Activator.CreateInstance(listType);
    ((IList)dynamicList).Add(fooContent);
    

    To dynamically invoke Markdown(IEnumerable contents)

    new Encoder().Markdown( (dynamic) dynamicList)
    

    Note the usage of dynamic in the method call. At runtime dynamicList will be List (additionally also being IEnumerable) since even usage of dynamic is still rooted to a strongly typed language the run time binder will select the appropriate Markdown method. If there is no exact type matches, it will look for an object parameter method and if neither match a runtime binder exception will be raised alerting that no method matches.

    The obvious draw back to this approach is a huge loss of type safety at compile time. Nevertheless code along these lines will let you operate in a very dynamic sense that at runtime is still fully typed as you expect it to be.

提交回复
热议问题