【问题标题】:C# return a type without having to know itC# 无需知道就返回一个类型
【发布时间】:2011-09-19 21:49:15
【问题描述】:

我想创建一个可用于依赖注入的工厂对象字典。

例如,假设我有一个名为 ServiceLocator 的静态类。应用程序可以使用:

ITest test = ServiceLocator<ITest>.GetInstance()

获取实现 ITest 接口的对象。

为了实现这一点,我首先创建了一个接口 IFactory

public interface IFactory<T>
{
   T GetInstance<T>();
}

然后,例如,ITest 的具体实现可能如下所示:

public class TestFactory : IFactory<ITest>
{
   public ITest GetInstance<ITest>
   {
     return new (ITest)OneImplementationOfITest();
   }

}

ServiceLocator 的定义如下:

public static class ServiceLocator
{
   private static Dictionary<string,object> m_Factories;

   public static T GetInstance<T>
   {
      string type = typeof(T).ToString();

      return ((IFactory<T>)Factories[type]).GetInstance();
   }
}

不幸的是,IFactory 中的 T 给出了编译器错误:

"T 必须是引用类型才能在泛型方法中用作参数 T..."

我可以想办法解决这个问题,例如定义 IFactory 而不是 IFactory:

public interface IFactory
{
  object GetInstance();
}

但随后用户需要自己投射对象:

ITest test = (ITest)ServiceLocator<ITest>.GetInstance();

这很尴尬并且可能导致错误(例如,没有正确投射)

如果有办法写就更好了:

ITest test = ServiceLocator.GetInstance("ITest") 但还没想好怎么做。

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    试试这个:

    public interface IFactory<T>
        where T: class
    {
       T GetInstance<T>();
    }
    

    这将T 限制为引用类型。顺便说一句,这是许多可用的generic type constraints 之一。

    【讨论】:

    • 其实我之前也试过,结果一样。但是,您的帖子给了我一个想法,让我在 Service Locator 中的 GetInstance 方法上进行尝试,并且成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2011-07-17
    • 2017-03-08
    • 2010-11-04
    • 1970-01-01
    相关资源
    最近更新 更多