gpt4 book ai didi

c# - 返回通用接口(interface)的工厂类

转载 作者:可可西里 更新时间:2023-11-01 08:21:58 24 4
gpt4 key购买 nike

我有几个具体使用了以下类型的接口(interface)

interface IActivity<T>
{
bool Process(T inputInfo);
}

具体类如下

class ReportActivityManager :IActivity<DataTable>
{
public bool Process(DataTable inputInfo)
{
// Some coding here
}
}

class AnalyzerActivityManager :IActivity<string[]>
{
public bool Process(string[] inputInfo)
{
// Some coding here
}
}

现在我如何编写工厂类来重新调整通用接口(interface),例如 IActivity。

class Factory
{
public IActivity<T> Get(string module)
{
// ... How can i code here
}
}

谢谢

最佳答案

您应该创建泛型方法,否则编译器将不知道返回值中T 的类型。当您拥有 T 时,您将能够根据 T 的类型创建事件:

class Factory
{
public IActivity<T> GetActivity<T>()
{
Type type = typeof(T);
if (type == typeof(DataTable))
return (IActivity<T>)new ReportActivityManager();
// etc
}
}

用法:

IActivity<DataTable> activity = factory.GetActivity<DataTable>();

关于c# - 返回通用接口(interface)的工厂类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com