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

问题描述 投票:1回答:1

我有此代码段:

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
    }
}

我只希望为X赋值,但是会出现2个编译错误。如何解决?

c# interface properties compilation explicit
1个回答
5
投票

实现接口明确地时,需要将变量强制转换为接口:

((Imy)o).X = 3;

o在您的代码中的类型为MyImpl。您需要将其强制转换为Imy才能使用接口属性。


或者,您可以将o声明为Imy

Imy o = new MyImpl();
o.X = 3;
© www.soinside.com 2019 - 2024. All rights reserved.