有没有一种方法可以在.NET中重载属性 [英] Is there a way to Overload a Property in .NET
问题描述
我已经做了很多方法重载,但是现在有一个我想重载属性的实例. Visual Studio中的IDE似乎允许这样做,因为我实际上可以设置两个重载,但是我收到一条错误消息,指出这是无效的,因为它们仅在类型上有所不同.我想我的语法中缺少什么?
I've done plenty of Method Overloading, but now I have an instance where I would like to Overload a Property. The IDE in Visual Studio seems to allow it, since I can actually set up the two overloads, but I get an error saying it is not valid because they only differ in type. I think I'm missing something in my syntax?
我希望能够使用两个(或多个)不同的自定义类作为我的媒体资源的类型.
I want to be able to use two (or more) different custom classes as the Type for my property.
Public Overloads Property myFlexibleProperty() As myCustomClass1
Get
Return _myFlexibleProperty1
End Get
Set(ByVal value As myCustomClass1)
_myFlexibleProperty1 = value
End Set
End Property
Public Overloads Property myFlexibleProperty() As myCustomClass2
Get
Return _myFlexibleProperty2
End Get
Set(ByVal value As myCustomClass2)
_myFlexibleProperty2 = value
End Set
End Property
到目前为止,我发现的所有帮助都与重载方法有关.尽管IDE允许我做什么,但我开始认为这是不可能的?
All of the help I have found so far has been concerning Overloading Methods. Despite what the IDE is letting me do, I'm beginning to think this is not possible?
推荐答案
要使过载某种方法或属性,您需要它接受一组不同的参数.由于VB.NET中的属性可以接受参数,因此我想您可以重载它们;但它们必须有所不同.
To overload something--method or property--you need for it to accept a different set of parameters. Since properties in VB.NET can accept parameters, I guess you can overload them; but they have to be different.
所以您可以这样做:
Public Overloads Readonly Property Average() As Double
Public Overloads Readonly Property Average(ByVal startIndex As Integer) As Double
但不是这样:
Public Overloads Readonly Property Average() As Double
Public Overloads Readonly Property Average() As Decimal
这篇关于有没有一种方法可以在.NET中重载属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!