我有一个课程如下。我只想让函数testa
和testb
得到相同的结果,testa有明确的类型字符串,而泛型类型是为testb
定义的:
public class testclass
{
public void testa(Func<String, String> action)
{
Console.WriteLine(action("what?"));
}
public void testall()
{
testa(tc =>
{
return tc;
});
testb<string>(tc =>
{
return tc;
});
}
public void testb<T>(Func<T, T> action)
{
**//How to write the body here to get the same result as testa do
//like action("abc");?**
}
}
答案 0 :(得分:5)
您不知道T
中的testb
是什么,因此除了default(T)
之外,您无法提供具体的值:
public void testb<T>(Func<T, T> action)
{
action(default(T)); // null for reference types, 0 for ints, doubles, etc
}
另一种选择是将测试值提供给testb
public void testb<T>(Func<T, T> action, T testValue)
{
action(testValue);
}
public void testall()
{
testa(tc =>
{
return tc;
});
testb<string>(tc =>
{
return tc;
}, "abc"); // now same result as testa
}
第三个选项是向new()
提供约束T
,然后你可以构建一个:
public void testb<T>(Func<T, T> action) where T : new()
{
action(new T());
}
小旁注:正如评论的那样,action
是一个通常给出函数表达式的名称,它没有返回(即Action<T>
或Action<string>
等)。它对您的代码没有任何影响,但可能会使其他程序员感到困惑。我们是一个迂腐的人!