Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 访问抽象类的成员_C#_Oop_Object Oriented Analysis - Fatal编程技术网

C# 访问抽象类的成员

C# 访问抽象类的成员,c#,oop,object-oriented-analysis,C#,Oop,Object Oriented Analysis,我有以下类层次结构: public abstract class BaseClass : IBaseInterface { public int PropertyA{ get { return this.propertyA; } set { this.propertyA = value; // ... some additional

我有以下类层次结构:

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对象(从基类继承)的PropertyA,我必须将该对象强制转换为基类a的祖先,如下所示:

// 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;
有没有一种方法可以让我重组这些类来消除演员阵容?这段代码是一个库的一部分,我的同事希望我去掉这个cast


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

首先在
((IBaseInterface)containingObject.BaseInterfaceObjectD)行中。PropertyA=42您正在将成员强制转换为声明它的相同类型,因此强制转换实际上不做任何事情

为了能够访问派生类中的PropertyA(因为您将其强制转换为接口),必须在接口中声明该属性,然后在基类中实现该属性

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中显示的问题,则可能是您的设置有问题。查看选项->文本编辑器->C#,并确保已打开IntelliSense,且未设置为隐藏任何内容。

您的描述和代码不太一致。请把一个和另一个排成一行。很抱歉。。。正在处理它。
((IBaseInterface)包含Object.BaseInterfaceObject)
,它已经是接口类型。你为什么要选演员?没有必要选演员-你可以简单地删除它。假设这个问题有一定的原因,你能引用你在不选演员时收到的错误消息吗?很简单,这可能就是问题所在。给定的实现不需要任何类型的转换,因此,如果OP必须转换为具体类型,那么这可能就是原因所在。