【问题标题】:Accessing properties of class through class interface通过类接口访问类的属性
【发布时间】:2014-06-11 10:24:30
【问题描述】:

为什么我不能通过它的接口(ItestClass)访问基类(testClass)的属性? 我创建了接口以避免在第三类 (newClass) 中显示实际的 Control (winforms/wpf) 属性。如果这不可能,有更好的方法吗?

public class testClass : Control, ItestClass
{
    public int Property1 { set; get; }
    public int Property2 { set; get; }
    public testClass() { }
}
public interface ItestClass
{
    int Property1 { get; set; }
    int Property2 { get; set; }
}

public class newClass : ItestClass
{
    public newClass()
    {
        // Why are the following statements are not possible?
        Property1 = 1;
        // OR
        this.Property1 = 1;
    }
}

【问题讨论】:

    标签: c# wpf winforms oop


    【解决方案1】:

    接口实际上并没有实现属性——你仍然需要在实现类中定义它们:

    public class newClass : ItestClass
    {
        int Property1 { get; set; }
        int Property2 { get; set; }
    
        // ...
    }
    

    编辑

    C# 不支持多重继承,因此您不能让testClass 继承Control 和另一个具体类。不过,您总是可以使用合成来代替。例如:

    public interface ItestClassProps
    {
        public ItestClass TestClassProps { get; set; }
    }
    
    public class testClass : Control, ItestClassProps
    {
        public ItestClass TestClassProps { set; get; }
    
        public testClass() { }
    }
    

    【讨论】:

    • @mason 不在newClass
    • 问题是我根本不想直接继承 testClass,因为它还会显示所有 Control 属性,而是继承了它的接口以避免这种情况。
    • 所以基本上我需要在第三类(newClass)中重新定义它们?
    • @Johnny 是的,因为 C# 不支持多重继承,在这种情况下你必须使用组合。
    • @Johnny 所以基本上,要么通过传递对“ItestClass”而不是“testClass”的引用来使用encapsulation通过给“testClass”一个“ItestClass”属性(见我上面的编辑)。
    猜你喜欢
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2013-07-30
    • 2014-12-28
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多