[英]C# Using Generic Class without Specifying Type
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. 在我的代码中的某些时候,我想用MyClass类型做任何事情。 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)?
或者我是否需要使MyClass成为某个子类(MyClassBase)或实现接口(IMyClass)?
I believe what you are need is to make MyMethod method generic and add constraint on its type parameter: 我相信你需要的是使MyMethod方法通用并在其类型参数上添加约束:
interface IMyInterface
{
void Foobar();
}
class MyClass<T>
{
public T Model
{
get;
protected set;
}
}
private void MyMethod<T>(MyClass<T> param) where T : IMyInterface
{
param.Model.Foobar();
}
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). 请注意,您将无法使用
Model
属性,因为它不能具有类型(除非您将其约束为基类型并显式实现非类型化属性)。
Yes, you need. 是的,你需要。 If type of generic class is undefined you need to create generic interface or using base-class...
如果未定义泛型类的类型,则需要创建通用接口或使用基类...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.