0

我有以下类层次结构:

public abstract class BaseClass : IBaseInterface
{

    public int PropertyA{
        get
        {
            return this.propertyA;
        }

        set
        {
            this.propertyA = value;
            // ... some additional processing ...
        }
    }
}

DerivedClassB : BaseClass
{
    // some other fields
}

public class ContainingClassC
{
    public IBaseInterface BaseInterfaceObjectD
    {
        get;
        set;
    }
}

现在,为了访问 DerivedClassB-Object(继承自 BaseClass)的 PropertyA,我必须将对象强制转换为 BaseClassA 的祖先,如下所示:

// This ContainingClassC is returned from a static, enum-like class:
// containingObject.PropertyA is DerivedClassB by default.
ContainingClassC containingObject = new ContainingClassC();

((IBaseInterface)containingObject.BaseInterfaceObjectD).PropertyA = 42;

有没有办法可以重组这些类以取消演员表?这段代码是图书馆的一部分,我的同事希望我摆脱演员阵容。

目标是简单地编写containingObject.BaseInterfaceObjectD.PropertyA = 42.

4

1 回答 1

0

首先,在该行中,((IBaseInterface)containingObject.BaseInterfaceObjectD).PropertyA = 42;您将成员转换为与其声明的类型相同的类型,因此该转换实际上并没有做任何事情。

为了能够访问派生类中的 PropertyA - 因为您将其转换为接口 - 必须在接口中声明属性,然后在 BaseClass 中实现。

public interface IBaseInterface{
  int PropertyA{get;set;}
}

public abstract class BaseClass : IBaseInterface{
  public int PropertyA{
    get{ return this.propertyA;}
    set {this.propertyA = value;}
   }
}

只要接口被正确实现,ProprtyA 就应该在基类、派生类中可用,或者将它们中的任何一个转换为接口类型。

如果只是 IntelliSense 中没有显示该属性的问题,则可能是您的设置有问题。查看 Options->Text Editor->C# 并确保您已打开 IntelliSense 并且未设置为隐藏任何内容。

于 2012-07-09T10:33:07.873 回答