C# 使用泛型类而不指定类型
我有一个这样创建的通用类:
public abstract class MyClass<T>
{
public T Model
{
get;
protected set;
}
}
在我的代码中的某个时刻,我想对 MyClass 类型的任何内容执行某些操作。比如:
private void MyMethod(object param)
{
myClassVar = param as MyClass;
param.Model....etc
}
这可能吗?或者我是否需要使 MyClass 成为某个东西的子类(MyClassBase)或实现一个接口(IMyClass)?
I have a generic class I have created as so:
public abstract class MyClass<T>
{
public T Model
{
get;
protected set;
}
}
And at some point in my code I want to do something with anything of MyClass type. Something like:
private void MyMethod(object param)
{
myClassVar = param as MyClass;
param.Model....etc
}
Is this possible? Or do I need to make MyClass be a subclass of something (MyClassBase) or implement an interface (IMyClass)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您需要的是使 MyMethod 方法通用并对其类型参数添加约束:
I believe what you are need is to make MyMethod method generic and add constraint on its type parameter:
不可以。
您需要继承非泛型基类或实现非泛型接口。
请注意,您将无法使用
Model
属性,因为它不能具有类型(除非您将其限制为基类型并显式实现非类型化属性)。No.
You need to inherit a non-generic base class or implement a non-generic interface.
Note that you won't be able to use the
Model
property, since it cannot have a type (unless you constrain it to a base type and implement an untyped property explicitly).是的,你需要。如果泛型类的类型未定义,您需要创建泛型接口或使用基类...
Yes, you need. If type of generic class is undefined you need to create generic interface or using base-class...