如何引用泛型类的所有实例?
我还没有完全理解泛型的某一方面。
假设我有一个 Generic 类:
public abstract SomeClass<T> where T : SomeInterface
{
public bool DoSomethingsWithT(T theItem)
{
//doStuff!!!
}
public virtual bool IsActive
{
get { return true; }
}
}
所以基本上我假设继承该类的版本是 Active 的,但我允许其中一些版本定义自己的版本。
现在稍后我将一个对象放入一个方法中,我知道该对象的类型为 SomeClass
但 T 可以是任何实现 SomeInterface
的类
public bool SomeMethod(object item)
{
var something = item as SomeClass;
return something.IsActive;
}
但这当然不起作用,因为没有名为 SomeClass
的类,而且我也无法执行 SomeClass
因为即使另一个类确实继承了该类,我也无法执行投射这个。
这通常是如何完成的?我们是否应该创建一个名为 SomeClass
的类,SomeClass
继承自该类,并在该类中定义 IsActive
属性。
如果我要创建继承 SomeClass
的项目集合,我会看到同样的问题。
I've not completely wrapped my head around one aspect of Generics.
Let's say I have a Generic class:
public abstract SomeClass<T> where T : SomeInterface
{
public bool DoSomethingsWithT(T theItem)
{
//doStuff!!!
}
public virtual bool IsActive
{
get { return true; }
}
}
So basicly I assume versions that inherit this class to be Active but I allow some of them to define their own.
Now later on I'm getting an object into a method that I know will be of the type SomeClass<T>
but T could be any class implementing SomeInterface
public bool SomeMethod(object item)
{
var something = item as SomeClass;
return something.IsActive;
}
But this of course doesn't work as there is no class named SomeClass
and I also can't do SomeClass<SomeInterface>
as even if another class does inherit from this I'm unable to cast this.
How is this normally done? Should we create a class named SomeClass
that SomeClass<SomeInterface>
inherits from and in that class we define the IsActive
property.
I'm seeing this same exact problem If I was gonna create a collection of items that inherit SomeClass<SomeInterface>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如何从类派生/实现包含常见行为的接口:
How about deriving from a class/implementing an interface that contains the common behaviour:
使用接口在泛型类上实现:
Use an interface to implement on the generic class:
是的,这正是您应该做的(也是通常的做法)。
或者您可以按照消费者的建议并使用接口而不是抽象类。这可能更好,因为它可以实现相同的目标,而不会将您限制在严格的类型层次结构中。
Yep, that's exactly what you should do (and is how this is normally done).
Or you could follow spender's advice and use an interface instead of an abstract class. This is probably better, as it accomplishes the same goal without restricting you to a rigid type hierarchy.
使用接口而不是类实现
刚刚意识到 IsActive 属性和您定义的属性不在接口中。
那么最好的方法是确定该类是否是
SomeClass
然后返回IsActive
Use the interface not the Class implementation
Just realized that the IsActive property and you are defining is not in the interface.
Then the best way to do this is to determine if the class is a
SomeClass
and then return theIsActive
不确定我是否正确,但是这个方法签名适用于 SomeMethod 吗?
Not sure if I've got this right, but would this method signature work for SomeMethod?