简体   繁体   English

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

[英]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.

相关问题 如何将DropDownList的DataTextField设置为显式实现的属性 - How to set DataTextField for DropDownList to explicitly implemented property 如何获取/设置并非总是实现的接口的属性 - How to get/set a property of an interface that is not always implemented 转换为未明确实现的接口? - Cast to not explicitly implemented interface? 如何正确使用显式实现的接口属性和wpf可见性? - How do I use an explicitly implemented interface property and wpf visiblity together properly? 为构造函数中显式实现的只读接口属性赋值 - Assign a value to an explicitly-implemented readonly interface property in a constructor 接口的全名和明确实现它的属性之间的区别 - Difference between interface's full name and explicitly implemented it's property 如何从 C# 中的接口隐藏已实现属性的设置方法? - How to hide set method of an implemented property from an interface in C#? 显式实现接口时如何访问static接口成员 - How to access static interface member when the interface is implemented explicitly 明确实现的接口和泛型约束 - Explicitly implemented interface and generic constraint 如何使用Type.InvokeMember来调用显式实现的接口方法? - How to use Type.InvokeMember to call an explicitly implemented interface method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM