使用泛型类型保持代码组织
我喜欢在编程时将事情分开。我认为这就是继承很重要的原因之一。
我使用的 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()
我知道我可以使用反射来解决这个问题,但我喜欢保持代码干净。我也想避免使用动态类型。
I like to keep things separate when programming. That is one of the reasons why inheritance is important I believe.
I am using a dll file that consists of a class that I cannot modify. the dll file contains ClassA to illustrate my example.
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()
{
}
}
why is there an error if object1 does implement ITemp inteface! object1 has the method MyCustomMethod()
I know I can use reflection to solve this but I like to keep my code clean. also I want to avoid using the dynamic type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ClassA 不实现 ITemp 接口。仅仅因为它具有与 ITemp 接口中的方法具有相同名称和签名的方法并不意味着它实现了该接口。需要声明该类才能显式实现它。
由于您无法扩展 ClassA,我能想到的最好的办法就是用适配器类型类包装它:
然后在您的 main 方法中:
ClassA doesn't implement the ITemp interface. Just because it has a method with the same name and signature as the method in the ITemp interface doesn't mean it implements that interface. The class would need to be declared to implement it explicitly.
Since you can't extend ClassA, the best thing I can think of would be to wrap it with an adapter type class:
Then in your main method:
您正在尝试使用鸭子打字。 C# 通常不支持
dynamic
类型之外的类型。 ClassA 需要实现该接口,正如您所指出的,它没有也不能实现。您可以使用代理包装类,但这可能是也可能不是一个好主意。You are trying to use duck typing. C# does not support that in general outside of the
dynamic
type. ClassA would need to implement the interface, as you noted it doesn't and can not be made to be. You could wrap class with a proxy but that may or may not be a good idea.