棘手的继承问题 [英] Tricky inheritance problem

查看:60
本文介绍了棘手的继承问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我有类FilterableList(Of T As CodeElement)。



FilterableList(Of T As CodeElement )有一个我想访问的静态方法。



我在给定时间所知道的是GetType(T)。我知道我需要做类似的事情;



 FilterableList(  ???)。方法()





但我无法弄清楚如何从T转换为类本身。 />


- Rix



我的尝试:



........................................ ............

解决方案

您似乎很困惑:FilterableList类具有与泛型参数无关的方法。要访问CodeElement方法,您需要提供T类的约束:

 Public Class FilterableList(Of T As CodeElement)
Inherits List(Of T) )
...
Public Sub DoSomething(x As T)
x.MyMethod()
End Sub
End Class





我正在尝试反转GetType()函数,以便我可以访问静态方法 - 这就是我不相信我需要实例的原因。 />


GetType(CodeElement)返回其类型;我可以获得该类型的类,然后访问其中的方法吗?




对于静态方法,您不需要GetType



CodeElement.MyStaticMethod()



就是你所需要的。您可以通过类名直接访问静态(在VB中共享)方法,甚至可以通过以下方式访问基类方法:

 公开  B 
公共 共享 Sub MyBaseMethod()
结束 Sub
结束 Class
公开 D
继承 B
公开 共享 Sub MyMethod( )
结束 Sub
结束
私有 Sub MyButton_Click(发件人 As Object ,e As EventArgs)
B.MyBaseMethod()
D.MyBaseMethod()
D.MyMethod()
结束 Sub


Hi
I have the class FilterableList(Of T As CodeElement).

FilterableList(Of T As CodeElement) has a static method which I want to access.

All I know at a given time is GetType(T). I know I need to do something like;

FilterableList(Of ???).method()



But I can't figure out how to convert from T to the class itself.

- Rix

What I have tried:

....................................................

解决方案

You seem confused: the FilterableList class has methods, which are not associated with the generic parameter. To access CodeElement methods, you need to provide a constraint of what classes T can be:

Public Class FilterableList(Of T As CodeElement)
	Inherits List(Of T)
...
	Public Sub DoSomething(x As T)
		x.MyMethod()
	End Sub
End Class



I'm trying to reverse the GetType() function so I can access a static method - that's why I don't believe I need the instance.

GetType(CodeElement) returns its type; can I get that type's class and then access the methods in it?


For static methods, you don't need GetType

CodeElement.MyStaticMethod()

is all you need. You can access static (Shared in VB talk) methods directly via the class name, and even access the base class methods that way:

Public Class B
	Public Shared Sub MyBaseMethod()
	End Sub
End Class
Public Class D
	Inherits B
	Public Shared Sub MyMethod()
	End Sub
End Class
Private Sub MyButton_Click(sender As Object, e As EventArgs)
	B.MyBaseMethod()
	D.MyBaseMethod()
	D.MyMethod()
End Sub


这篇关于棘手的继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆