c# - Is there a way to initialize EII property within constructor?
问题描述
Let's start with code from MS page:
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:
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.
解决方案
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, e.g.:
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...)
推荐阅读
- javascript - 如何配置 express-handlebars 以将其与 nodemailer 链接?
- spring - Play 框架中的 @ComponentScan
- python - SELENIUM Python - 尝试访问某些数据进行处理
- tsql - SQL:使用电子表格中的数据更新多行
- javascript - 带有 Wild Web Dev 的 Eclipse 2020 - Javascript 颜色问题
- go - 如何在go中处理异步go函数值
- javascript - 使函数返回子函数,但默认为另一个函数(Node.js/JS)
- java - 使用十进制格式 Android JAVA 格式化 ValueAmimator setText
- node.js - React npm start not working at it 重新安装时失败
- c++ - 将枚举重构为枚举类阴影命名空间