[英]C# Generic Interface and Factory Pattern
我正在尝试创建一个通用接口,其中一种方法的参数类型由泛型定义
编辑
在意识到我可能通过在工厂创建方法中指定类型参数来混淆问题之后,我稍微改变了这个问题。 我有两种类型的 API 调用,我需要向第 3 方 API 进行调用。 第一个使用 int 的 Id 从 API 检索记录。 第二个还从 API 检索记录,但 Id 是一个字符串 (guid)。 对于每种记录类型(ClientEntity 和 InvoiceEntity),我都有一个 class,它们都实现了一个通用接口,我在其中传入了 Id 类型
这是我在其中声明带有 id 参数的方法的接口
public interface IGeneric<TId>
{
void ProcessEntity(TId id);
}
我在几个类中实现了接口,一个将 id 设置为 int,另一个设置为 string。
public class ClientEntity: IGeneric<int> // Record with Id that is an int
{
public void ProcessEntity(int id)
{
Console.WriteLine(id);
// call 3rd party API with int Id
}
}
public class InvoiceEntity: IGeneric<string> // Record with Id that is a string (guid)
{
public void ProcessEntity(string id)
{
Console.WriteLine(id);
// call 3rd party API with string Id
}
}
我想知道的是如何在工厂模式中使用它?
public static class GenericFactory
{
public static IGeneric<WhatGoesHere> CreateGeneric(string recordType)
{
if (recordType == "Client")
{
return new ClientEntity();
}
if (type == "Invoice")
{
return new InvoiceEntity();
}
return null;
}
}
目标是使用工厂实例化正确的 class 以便我可以调用 ProcessEntity 方法
编辑
我不想将通用类型传递给工厂方法,因为工厂创建的 class 应该处理它。 当我创建 object 时,我不知道需要什么 Id 类型,我希望工厂处理
例如
var myGeneric = GenericFactory.CreateGeneric("Client");
myGeneric.ProcessEntity("guid")
或者
var myGeneric = GenericFactory.CreateGeneric("Invoice");
myGeneric.ProcessEntity(1234)
我希望这是有道理的
通常对于那个工厂使用一些DI容器(例如,当GenericInt或GenericString具有依赖关系时DI可能很有用),但是为了演示如何解决这个问题:
void Main()
{
GenericFactory.CreateGeneric<int>();
GenericFactory.CreateGeneric<string>();
}
public static class GenericFactory
{
private static Dictionary<Type, Type> registeredTypes = new Dictionary<System.Type, System.Type>();
static GenericFactory()
{
registeredTypes.Add(typeof(int), typeof(GenericInt));
registeredTypes.Add(typeof(string), typeof(GenericString));
}
public static IGeneric<T> CreateGeneric<T>()
{
var t = typeof(T);
if (registeredTypes.ContainsKey(t) == false) throw new NotSupportedException();
var typeToCreate = registeredTypes[t];
return Activator.CreateInstance(typeToCreate, true) as IGeneric<T>;
}
}
public interface IGeneric<TId>
{
TId Id { get; set; }
void ProcessEntity(TId id);
}
public class GenericInt : IGeneric<int>
{
public int Id { get; set; }
public void ProcessEntity(int id)
{
Console.WriteLine(id);
}
}
public class GenericString : IGeneric<string>
{
public string Id { get; set; }
public void ProcessEntity(string id)
{
Console.WriteLine(id);
}
}
你应该可以做这样的事情:
public static class GenericFactory
{
public static IGeneric<T> CreateGeneric<T>()
{
if (typeof(T) == typeof(string))
{
return (IGeneric<T>) new GenericString();
}
if (typeof(T) == typeof(int))
{
return (IGeneric<T>) new GenericInt();
}
throw new InvalidOperationException();
}
}
你会像这样使用它:
var a = GenericFactory.CreateGeneric<string>();
var b = GenericFactory.CreateGeneric<int>();
请注意,这使用强类型调用,而不是将类型名称作为字符串传递(可能是您实际想要的,也可能不是)。
如果您想要为类型名称传递字符串,则必须返回一个object
因为无法返回实际类型:
public static object CreateGeneric(string type)
{
switch (type)
{
case "string": return new GenericString();
case "int": return new GenericInt();
default: throw new InvalidOperationException("Invalid type specified.");
}
}
显然,如果你有一个object
你通常必须将它强制转换为正确的类型才能使用它(这要求你知道实际的类型)。
或者,您可以使用反射来确定它包含的方法,并以这种方式调用它们。 但是你仍然需要知道类型才能传递正确类型的参数。
我认为你在这里尝试做的不是正确的方法,一旦你开始尝试使用它,你会发现它。
Hacky解决方案:使用dynamic
然而,有一种方法可以得到你想要的东西:使用dynamic
如下(假设你正在使用上面的object CreateGeneric(string type)
工厂方法):
dynamic a = GenericFactory.CreateGeneric("string");
dynamic b = GenericFactory.CreateGeneric("int");
a.ProcessEntity("A string");
b.ProcessEntity(12345);
请注意, dynamic
使用反射和代码生成,这可能会使初始调用相对较慢。
还要注意,如果将错误的类型传递给通过dynamic
访问的方法,您将得到一个讨厌的运行时异常:
dynamic a = GenericFactory.CreateGeneric("string");
a.ProcessEntity(12345); // Wrong parameter type!
如果运行该代码,则会出现此类运行时异常:
Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'ConsoleApplication1.GenericString.ProcessEntity(string)' has some invalid arguments
at CallSite.Target(Closure , CallSite , Object , Int32 )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
at ConsoleApplication1.Program.Main() in D:\Test\CS6\ConsoleApplication1\Program.cs:line 71
如果你想使用静态类,但标记正确的答案很好但是如果你想返回DI注入类型而不是新建一个对象怎么办? 我建议如下!
public interface IGenericFactory
{
IGeneric<T> GetGeneric<T>() where T : class;
}
public class GenericFactory: IGenericFactory
{
private readonly IGeneric<int> intGeneric;
private readonly IGeneric<string> stringGeneric;
public GenericFactory(IGeneric<int> intG, IGeneric<string> stringG)
{
intGeneric = intG;
stringG = stringG;
}
public IGeneric<T> GetGeneric<T>() where T : class
{
if (typeof(T) == typeof(IGeneric<int>))
return (IGeneric<T>)Convert.ChangeType(intGeneric, typeof(IGeneric<T>));
if (typeof(T) == typeof(IGeneric<string>))
return (IGeneric<T>)Convert.ChangeType(stringGeneric,typeof(IGeneric<T>));
else
throw new NotSupportedException();
}
}
请注意,为了清晰起见,我只是在构造函数中注入了两个预期的返回类型。 我可以将工厂实现为Dictionary并将返回对象注入此Dictionary。 希望能帮助到你。
public class Program
{
public static void Main(string[] args)
{
List<Number> list = new();
Do(list);
}
public static void Do<T>(List<T> list)
{
list.Add(Factory<T>.Create());
}
}
public abstract class Factory<T>
{
private static Object ConcreteF()
{
if (typeof(T) == typeof(Number))
return new ChildOfFactory();
throw new Exception("");
}
public static T Create(int max)
{
return (Factory<T>)ConcreteF()).Build();
}
protected abstract T Build();
}
我想你不想输入类似于 LINQ 方法的类型参数。 然而,这背后的魔力发生了,因为类型参数用于普通参数定义。 例如,在ToList<string>()
方法中,您可以看到在括号之间使用了TSource
。
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source);
如果从IEnumerable<string>
调用时调用ToList()
而不是ToList<string>()
,编译器就是这样知道你想要List<string>
string>
但是,我认为您的工厂方法中根本不需要泛型类型参数。 您所要做的就是创建TGeneric<TId>
的非通用版本
public interface IGeneric { }
public interface IGeneric<TId> : IGeneric
{
void ProcessEntity(TId id);
}
并从CreateGeneric
方法中删除<WhatGoesHere>
:
public static IGeneric CreateGeneric(string recordType)
{
if (recordType == "Client")
{
return new ClientEntity();
}
if (recordType == "Invoice")
{
return new InvoiceEntity();
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.