gpt4 book ai didi

c# - C# 子类中的 protected 属性是否应该隐藏对父类公共(public)属性的访问?

转载 作者:IT王子 更新时间:2023-10-29 04:12:30 28 4
gpt4 key购买 nike

我有以下代码:

public class Parent
{
public string MyField { get; set; }
}

public class Child : Parent
{
protected new int MyField { get; set; }
}

我尝试通过以下方式访问它:

static void Main(string[] args)
{
Child child = new Child();
child.MyField = "something";
}

Visual studio 2008 编译时没有注释,但在 Mono(2.4.2,Ubuntu)下我收到错误消息

'HideTest.Child.MyField' is inaccessible due to its protection level (CS0122)

是一种实现还是另一种更符合这里的标准?

编辑:感谢所有指出错误设计的人。不幸的是,它是一个第三方库,对其进行重大更改是不切实际的。

最佳答案

来自 ECMA-334 (C# 规范)§10.7.1.2:

A declaration of a new member hides an inherited member only within the scope of the new member.

您可以通过在 Microsoft 的实现上运行此测试来查看此行为。

using System;
using NUnit.Framework;

namespace ScratchPad
{
[TestFixture]
public class Class1
{
[Test]
public void InheritanceHiding()
{
var b = new Base();
var d = new Derived();

var baseSomeProperty = b.SomeProperty;
var derivedSomeProperty = d.SomeProperty;

b.GetSomeProperty();
d.GetSomeProperty();
}
}

public class Base
{
public string SomeProperty
{
get
{
Console.WriteLine("Getting Base.SomeProperty");
return "Base.SomeProperty";
}
}

public string GetSomeProperty()
{
return SomeProperty;
}
}

public class Derived : Base
{
protected new int SomeProperty
{
get
{
Console.WriteLine("Getting Derived.SomeProperty");
return 3; //Determined by random roll of the dice.
}
}

public new int GetSomeProperty()
{
return SomeProperty;
}
}
}

输出:

Getting Base.SomeProperty    //(No Controversy)  
Getting Base.SomeProperty //(Because you're calling from public scope and the new member is in protected scope, there is no hiding)
Getting Base.SomeProperty //(No Controversy)
Getting Derived.SomeProperty //(Now because you're calling from protected scope, you get the protected member).

因此,您从 Main() 访问的属性应该是基类属性(在 MS.NET 中),而不是派生属性(在 Mono 中),因为新派生成员仅在 protected 范围内隐藏“旧”基础成员。

根据规范,Mono 在这里做错了。

关于c# - C# 子类中的 protected 属性是否应该隐藏对父类公共(public)属性的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2845276/

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