gpt4 book ai didi

c# - 为什么我不能从动态对象访问 Internal/Friend 属性?

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:00 28 4
gpt4 key购买 nike

我将首先展示 VB.NET 代码,因为它的 C# 等效代码的行为更令人困惑(见下文)

考虑以下三个类:

Public Class BaseClass
Private Shared Rand As New Random
Public Shared Function CreateDerived() As BaseClass
Return If(Rand.Next(1, 3) = 1, New DerivedClass1(), New DerivedClass2())
End Function
End Class

Public Class DerivedClass1
Inherits BaseClass

Sub New()
MyProperty = 1
End Sub

Friend Property MyProperty As Integer
End Class

Public Class DerivedClass2
Inherits BaseClass

Sub New()
MyProperty = 2
End Sub

Friend Property MyProperty As Integer
End Class

现在,当我尝试做这样的事情时:

Sub Foo()
Dim targetClass As BaseClass = BaseClass.CreateDerived()

Dim Casted
If TypeOf (targetClass) Is DerivedClass1 Then
Casted = DirectCast(targetClass, DerivedClass1)
ElseIf TypeOf (targetClass) Is DerivedClass2 Then
Casted = DirectCast(targetClass, DerivedClass2)
Else
Exit Sub
End If

Console.WriteLine(Casted.MyProperty) 'Throws an exception.
End Sub

我似乎无法访问 MyProperty,并且收到以下异常:

Public member 'MyProperty' on type 'DerivedClass1' not found.

因此,当我将 MyProperty 的访问级别更改为 Public 时,代码会按预期工作。

奇怪的是,当我在 VS 2015 上尝试与上述代码等效的 C# 时,它工作正常,但是 在 .NET Fiddler 上,它不会。

Here's the C# example在 .NET Fiddler 上,我得到与 VB.NET 相同的行为。

那么,我做错了什么吗?

最佳答案

我无法回答这个问题的原因,但我可以提供解决方法。

创建一个Interface 并在您的BaseClass 中实现它。然后,您可以将其声明为接口(interface),而不是将 Casted 声明为 Object,这将正确公开您想要的属性,并使用与以前相同的访问修饰符。

完整示例如下。

Sub Foo()
Dim targetClass As BaseClass = BaseClass.CreateDerived()

Dim Casted As Interf
If TypeOf (targetClass) Is DerivedClass1 Then
Casted = DirectCast(targetClass, DerivedClass1)
ElseIf TypeOf (targetClass) Is DerivedClass2 Then
Casted = DirectCast(targetClass, DerivedClass2)
Else
Exit Sub
End If

Console.WriteLine(Casted.MyProperty) 'Throws an exception.
End Sub

Friend Interface Interf
Property MyProperty As Integer
End Interface

Public Class BaseClass
Implements Interf

Private Shared Rand As New Random

Friend Overridable Property MyProperty As Integer Implements Interf.MyProperty

Public Shared Function CreateDerived() As BaseClass
Return If(Rand.Next(1, 3) = 1, New DerivedClass1(), New DerivedClass2())
End Function
End Class

Public Class DerivedClass1
Inherits BaseClass

Sub New()
MyProperty = 1
End Sub

Friend Overrides Property MyProperty As Integer
End Class

Public Class DerivedClass2
Inherits BaseClass

Sub New()
MyProperty = 2
End Sub

Friend Overrides Property MyProperty As Integer
End Class

关于c# - 为什么我不能从动态对象访问 Internal/Friend 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47219595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com