简体   繁体   English

有没有办法在构造函数中初始化 EII 属性?

[英]Is there a way to initialize EII property within constructor?

Let's start with code from MS page:让我们从 MS 页面的代码开始:

interface ILeft
{
    int P { get;}
}
interface IRight
{
    int P();
}

class Middle : ILeft, IRight
{
    public int P() { return 0; }
    int ILeft.P { get { return 0; } }
}

I would like to change Middle in such way, the EII property is once initialized, something like this:我想以这种方式更改Middle ,EII 属性一旦初始化,如下所示:

class Middle : ILeft, IRight
{
    public int P() { return 0; }
    int ILeft.P { get; }

    Middle()
    {
        ILeft.P = 0;    
    }
}

Above code does not compile, thus my question -- is there a syntax for doing this?上面的代码无法编译,因此我的问题是 - 是否有这样做的语法

I am asking about syntax, because brute force way would be to declare private field and redirect ILeft.P getter to return data from it.我问的是语法,因为蛮力方法是声明私有字段并重定向ILeft.P getter 以从中返回数据。

I think the only other possibility besides your suggested approach of using a backing field rather than an auto-property is to use the property initializer syntax, eg:我认为除了您建议的使用支持字段而不是自动属性的方法之外,唯一的另一种可能性是使用属性初始值设定项语法,例如:

int ILeft.P { get; } = 0;

Of course with this you can't initialize based on, say, an argument passed to the constructor, so it provides only limited additional flexibility.当然,你不能根据传递给构造函数的参数进行初始化,因此它只能提供有限的额外灵活性。

(There is a proposal to add " primary constructors " to the C# language, which might make it possible to initialize a get-only explicitly implemented interface property based on a constructor argument, though as far as I know there's no timeline for its inclusion in the language so I wouldn't hold your breath...) (有一个建议将“ 主构造函数”添加到 C# 语言中,这可能使基于构造函数参数初始化仅获取显式实现的接口属性成为可能,但据我所知,没有时间表将其包含在语言,所以我不会屏住你的呼吸......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Entity Framework 中初始化一个已经有构造函数的属性 - Initialize a property in Entity Framework that already has a constructor 有没有办法在VBA中重载类的构造函数/初始化过程? - Is there a way to overload the constructor / initialize procedure for a class in VBA? 在类构造函数中初始化枚举的正确方法 - Correct way to initialize Enums inside a class constructor 有没有办法在C#中用构造函数初始化字段? - Is there a way to initialize fields out of constructor in C#? 有没有办法在不使用构造函数的情况下初始化结构的成员? - Is there a way to initialize members of a struct without using a constructor? 仅在受保护的构造函数中设置的属性 - Property that is set only within protected constructor 有没有办法 select 列表中的一个属性? - Is there a way to select a Property within a List? 如果我的课程有一个带有私有字段用于存储的属性,我应该使用私有字段还是该属性在构造函数中对其进行初始化? - If my class has a property with a private field for storage, should i use the private field or the property to initialize it in the constructor? 初始化类属性的另一种方法是类类型? - Alternate way to initialize class property which is of type class? 使用属性的集合验证在构造函数中设置私有字段 - Set private field within constructor using set validation from property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM