如何设置显式实现的接口的属性?

Tro*_*yvs 2 c# compilation explicit properties interface

我有这个代码片段:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我只是想为 X 赋值,但得到 2 个编译错误。如何解决?

Ren*_*ogt 8

显式实现接口时,需要将变量强制转换为接口:

((Imy)o).X = 3;
Run Code Online (Sandbox Code Playgroud)

oMyImpl您代码中的类型。您需要将其Imy显式转换为使用接口属性。


或者,您可以声明oImy

Imy o = new MyImpl();
o.X = 3;
Run Code Online (Sandbox Code Playgroud)