簡體   English   中英

C#通用接口

[英]C# Generic interface

我需要將泛型類型參數傳遞給接口。 我有一個名稱類型的字符串。

我有這樣的事情:

string type = "ClassType";
Type t = Type.GetType("ClassType");

IProvider<t> provider = (IProvider<t>)someObject;

這對我不起作用。 這樣做的正確方法是什么? 謝謝。

在C#(和CLR)版本的泛型中,你真正想要做的是什么。 指定通用參數時,它必須是......

  • 代碼中的具體類型
  • 另一個通用參數

此信息必須綁定在程序集的元數據中。 無法以這種方式從元數據中的字符串表達類型名稱。

可以在運行時基於字符串名稱綁定泛型,但這需要反射。

我相信這就是你要找的東西=> Type.MakeGenericType

以下是使用反射加載泛型類型的示例。

using System;
namespace GenericCastRuntime
{
    class Program
    {
        static void Main(string[] args)
        {
            string type = "GenericCastRuntime.Program+Provider`1";
            Type t = Type.GetType(type);

            string genericType = "System.String";
            Type gt = Type.GetType(genericType);

            var objType = t.MakeGenericType(gt);
            var ci = objType.GetConstructor(Type.EmptyTypes);
            var obj = ci.Invoke(null);
            IProvider provider = obj as IProvider;
        }

        public class Provider<T> : IProvider<T>
        {
            public T Value { get; set; }

            object IProvider.Value
            {
                get { return this.Value; }
                set
                {
                    if (!(value is T)) throw new InvalidCastException();
                    this.Value = (T)value;
                }
            }

        }

        public interface IProvider { object Value { get; set; } }
        public interface IProvider<T> : IProvider { T Value { get; set; } }
    }
}

這是一個簡單的例子:

    public static object DynamicallyCreateGeneric(Type GenericTypeSource, Type SpecificTypeSource)
    {
        System.Type SpecificType = 
            GenericTypeSource.MakeGenericType(
            new System.Type[] { SpecificTypeSource }
            );

        return Activator.CreateInstance(SpecificType);
    }

......然后,例如:

        string type = "System.String";
        Type t = Type.GetType(type);

        var DynamicallyCreatedGeneric = DynamicallyCreateGeneric(typeof(List<>), t);

        System.Diagnostics.Debugger.Break();

適應您的實施和品味。 當然,這種方法並不理想。 泛型的最佳部分之一是類型編譯器級別類型安全性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM