C# 基于C的泛型类型参数的条件代码#
我在C#中有一个方法,它接收一个泛型类型作为参数:C# 基于C的泛型类型参数的条件代码#,c#,asp.net-mvc,types,C#,Asp.net Mvc,Types,我在C#中有一个方法,它接收一个泛型类型作为参数: private void DoSomething<T>(T param) { //... } 有更好的方法吗?可能使用开关盒或我不知道的其他方法?可以为特定类型创建特定方法 private void DoSomething<T>(T param) { //... } private void DoSomething(int param) { /* ... */
private void DoSomething<T>(T param)
{
//...
}
有更好的方法吗?可能使用
开关盒
或我不知道的其他方法?可以为特定类型创建特定方法
private void DoSomething<T>(T param)
{
//...
}
private void DoSomething(int param) { /* ... */ }
private void DoSomething(string param) { /* ... */ }
private void DoSomething(T参数)
{
//...
}
私有void DoSomething(int参数){/*…*/}
私有void DoSomething(字符串参数){/*…*/}
如果项目/逻辑结构允许,最好将DoSomething移到T中,并使用IDoSomething接口进行描述。这样你就可以写:
private void DoSomething<T>(T param) where T:IDoSomething
{
param.DoSomething()
}
private void DoSomething(T参数),其中T:IDoSomething
{
参数DoSomething()
}
如果这不是一个选项,那么您可以设置规则字典
var actionsByType = new Dictionary<Type, Action<T /*if you neeed that param*/>(){
{ Type1, DoSomething1 },
{ Type2, DoSomething2 },
/..
}
var actionsByType=newdictionary只需使用重载而不是泛型 如前所述,如果是简单的情况,请使用重载。任何陌生人你都可以适应这一点(它的快速和肮脏的道歉)
类程序
{
接口
{
无效剂量测定(T参数);
}
课堂测试:我有东西,我有东西
{
公共无效剂量测定(int参数)
{
}
公共void DoSomething(字符串参数)
{
}
}
静态void Main(字符串[]参数)
{
剂量测定法(4);
}
静态空隙剂量测定(T参数)
{
var测试=新测试();
var cast=测试作为一种东西;
if(cast==null)抛出新异常(“未处理类型”);
铸造剂量测定(参数);
}
}
一般来说,如果您正在做一些固有的类型特定的事情,那么泛型方法是错误的工具。也许创建一个具有特定类型重载的方法,该方法在完成时调用泛型方法?你能解释一下你想做什么吗?这可能有助于阅读@GlorinOakenfoot,我也想到了重载;我在寻找不同的想法和选择。你是对的,这是一条路要走。尽管如此,我从每个答案中都得到了有趣的反馈,谢谢大家(+1)。我正要接受你们的第一个想法,非常好!但我的项目结构不允许这样做。第二种方法也不错,但我将首先尝试使用简单的重载。谢谢
var actionsByType = new Dictionary<Type, Action<T /*if you neeed that param*/>(){
{ Type1, DoSomething1 },
{ Type2, DoSomething2 },
/..
}
private void DoSomething<T>(T param){
//some checks if needed
actionsByType[typeof(T)](param/*if param needed*/);
}
class Program
{
interface IDoSomething<T>
{
void DoSomething(T param);
}
class Test : IDoSomething<int>, IDoSomething<string>
{
public void DoSomething(int param)
{
}
public void DoSomething(string param)
{
}
}
static void Main(string[] args)
{
DoSomething(4);
}
static void DoSomething<T>(T param)
{
var test = new Test();
var cast = test as IDoSomething<T>;
if (cast == null) throw new Exception("Unhandled type");
cast.DoSomething(param);
}
}