【发布时间】:2012-01-15 08:01:26
【问题描述】:
我喜欢在编程时把事情分开。这就是我认为继承很重要的原因之一。
我使用的 dll 文件包含一个我无法修改的类。 dll 文件包含 ClassA 来说明我的示例。
class Program
{
static void Main(string[] args)
{
ClassA object1 = new ClassA();
SomeMethod<ClassA>(object1 ); // error because " a does not implement ITemp"
}
static T SomeMethod<T>(T input)
where T:ITemp // make sure input has a method MyCustomMethod
{
input.MyCustomMethod();
return input;
}
// create this interface so that compiler does not complain when
// calling MyCustomMethod in method above
interface ITemp
{
void MyCustomMethod();
}
}
// classA is a sealed class in a dll file that I cannot modify
public class ClassA
{
public void MyCustomMethod()
{
}
}
如果 object1 确实实现了 ITemp 接口,为什么会出现错误! object1 有方法 MyCustomMethod()
我知道我可以使用反射来解决这个问题,但我喜欢保持我的代码干净。我也想避免使用动态类型。
【问题讨论】:
标签: c# generics reflection dynamic