c# - 如何设置显式实现的接口(interface)的属性?

标签 c# interface properties compilation explicit

我有这个代码片段:

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 个编译错误。如何解决?

最佳答案

当您显式实现接口(interface)时,您需要将变量强制转换为接口(interface):

((Imy)o).X = 3;

o 在您的代码中属于 MyImpl 类型。您需要将其显式转换为 Imy 才能使用接口(interface)属性。

<小时/>

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

Imy o = new MyImpl();
o.X = 3;

关于c# - 如何设置显式实现的接口(interface)的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60598638/

相关文章:

java - 为什么不能将返回 List 的方法的返回值分配给 ArrayList 变量?

c# - Visual Studio : Collecting the members of an interface in the same region

vb.net - 接口(interface)需要继承基类

c# - 将 PDF 文件从 Fiddler 上传到 WebAPI 方法导致 415 Unsupported Media Type

c# - 将 C dll 和方法导入到 c# 中

c# - 啊,对服务层感到如此困惑

c# - 在 LINQ 中,如何修改现有的 LINQ 扩展方法以添加 "By"选择器,即将 Func<T> TResult 添加到函数签名?

c# - 以编程方式生成属性

objective-c - 在 '' 类型的对象上找不到属性 'id'