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?
Based on your second method if you want to call that using c# Func , here is the code below.
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. 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>
?
Or, alternatively, if you don't want to use 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>;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.