[英]Delegate for generic method return <T>
I have a method - 我有一种方法-
public T GetField<T> (string tableName, string fieldName)
{
//Code
}
I need a delegate to hold this method. 我需要一个委托来保持此方法。 Not sure how to declare delegate for above method.
不知道如何为上述方法声明委托。
Now if I change my method 现在如果我改变方法
public T GetField<T> (string tableName, string fieldName, params IDbDataParameter[] parameters)
{
//Code
}
public T Func<string,string ,string,IDbDataParameter[],T> GetFieldAction = GetField;// This is wrong
Any suggestion? 有什么建议吗? Is it possible?
可能吗? Can I have a delegate which can hold generic return type method?
我可以有一个可以容纳通用返回类型方法的委托吗?
Is there any Func() workaround? 有任何Func()解决方法吗?
Based on your second method if you want to call that using c# Func , here is the code below. 如果要使用c#Func调用第二种方法,则基于以下方法。
public class Stackoverflow<T>
{
public static Func<string,string,IDbDataParameter[],T> CallingFunc;
public static T GetField(string tableName, string fieldName, params IDbDataParameter[] parameters)
{
//Code
return default(T);
}
}
public class MainProgram
{
static void Main(string[] args)
{
Stackoverflow<int>.CallingFunc = Stackoverflow<int>.GetField;
Stackoverflow<int>.CallingFunc("SampleTableName", "SampleField", new[]{
new SqlParameter{DbType = DbType.Int32,Size = sizeof(Int32),ParameterName = "Id",Direction = ParameterDirection.Input},
new SqlParameter{DbType = DbType.String,Size = 100,ParameterName = "name",Direction = ParameterDirection.Output}
});
}
}
Main method can't be call under generic class, so it's reside in other class. Main方法不能在泛型类下调用,因此它位于其他类中。 This workaround also can be possible using generic delegates like below
也可以使用以下通用委托来解决此问题
public class Stackoverflow<T>
{
public delegate T CallingDelegate(string tableName, string fieldName, params IDbDataParameter[] parameters);
public static T GetField(string tableName, string fieldName, params IDbDataParameter[] parameters)
{
//Code
return default(T);
}
}
public class MainProgram
{
static void Main(string[] args)
{
Stackoverflow<int>.CallingDelegate del = Stackoverflow<int>.GetField;
del("SampleTableName", "SampleField", new[]{
new SqlParameter{DbType = DbType.Int32,Size = sizeof(Int32),ParameterName = "Id",Direction = ParameterDirection.Input},
new SqlParameter{DbType = DbType.String,Size = 100,ParameterName = "name",Direction = ParameterDirection.Output}
});
}
}
Why not Func<string, string, T>
? 为什么不使用
Func<string, string, T>
?
Or, alternatively, if you don't want to use Func
: 或者,或者,如果您不想使用
Func
:
delegate T MyDelegate<T>(string tableName, string fieldName);
EDIT: Example code which addresses your comment: 编辑:解决您的评论的示例代码:
delegate T MyDelegate<T>(string tableName, string fieldName, params IDbDataParameter[] parameters);
private T GetField<T>(string tableName, string fieldName, params IDbDataParameter[] parameters)
{
return default(T);
}
void Main()
{
MyDelegate<int> del = this.GetField<int>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.