[英]How to set property of explicitly implemented interface?
I've this code snippet:我有这个代码片段:
public interface Imy
{
int X { get; set; }
}
public class MyImpl : Imy
{
private int _x;
int Imy.X
{
get => _x;
set => _x = value;
}
}
class Program
{
static void Main(string[] args)
{
var o = new MyImpl();
o.Imy.X = 3;//error
o.X = 3;//error
}
}
I just wish to assign value to X, but get 2 compilation errors.我只是想为 X 赋值,但得到 2 个编译错误。 How to fix it?如何解决?
When you implement the interface explicitly , you need to cast the variable to the interface:显式实现接口时,需要将变量强制转换为接口:
((Imy)o).X = 3;
o
is of type MyImpl
in your code. o
在您的代码中MyImpl
类型。 You need to cast it to Imy
explicitly to use the interface properties.您需要将其显式转换为Imy
才能使用接口属性。
Alternativly, you could declare o
as Imy
:或者,您可以将o
声明为Imy
:
Imy o = new MyImpl();
o.X = 3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.