在 C# 中属性 class 名称之前使用 new 关键字是为了什么?

What for is new keyword is used in C# before attribute class name?

在属性 class 名称之前使用 C# new 关键字的目的是什么?

我正在使用 Rider,它经常建议在属性名称前放置一个新关键字。

public class MyClass
{
   new AttributeClass attribute;

   ...    
}

As explained in documentation:

If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.

new 属性上的关键字可以让您覆盖它的类型。当被视为基本类型时,对象将不会知道它。它也可以在同一对象实例的基类型和派生类型中具有不同的值。不用说,这可能会导致一些非常混乱的错误。

考虑这个例子:

class Super
{
    int Id;
}

class Sub : Super
{
    new string Id;
}

static class Another
{
    static void AssignId(Super test, int val)
    {
        test.Id = val;
    }

    static Super ShowId(Super test)
    {
        return test.Id;
    }
}

...

var test = new Sub
{
    Id = "SUB123"
};

Another.AssignId(test, 123);
Console.WriteLine(Another.ShowId(test)); // 123
Console.WriteLine(test.Id); // SUB123

class 属性 上的 new 关键字用于从基础 class 替换可覆盖的 属性。

例如

void Main()
{
    var objA = new Base {
        Prop = "test"
    };

    var objB = new Derived {
        Prop = 42
    };
}
public class Base
{
    public virtual string Prop { get; set; }
}
public class Derived : Base
{
    public new int Prop { get; set; }
}

Read more...

其他 post 用户已经解释了关键字的含义。

问题不是 100% 清楚,但操作员可能一直在问为什么在这种特殊情况下建议这样做。

当重构工具检测到您在派生 class 中实现了一个与基 class 中的虚拟成员同名的成员时,它们会建议您使用 new 关键字。 =10=]

发生这种情况时,您有一些选择。

如果打算扩展基础 class 功能,请使用 override 关键字。

或者,如果您想完全替换基本实现,请使用 new 关键字。

或者,如果命名冲突只是巧合,则重命名派生 class 中的成员。

我删除了这个 post 然后取消删除它,因为我无法确定这个问题是否可以用给定的信息来回答。我假设 op 正在谈论在派生类型上声明成员时被提示使用 new 关键字。如果他们试图在不使用 new 关键字的情况下实例化一个引用类型,他们会得到一个编译器错误;不是建议...但是又是谁从给出的例子中知道的呢。