属性仅在父类是特定的时才可用

时间:2013-08-25 16:42:01

标签: c# properties

这可能很简单,但我是C#的新手。一些课程:

public class Extension {
      Public string Name;
      Public List<View> Views;
}

public class Module : Extension {
     // ...
}

public class Component : Extension {
    // ...
}

public class View {
    // ...
}

还有一个系列:

List<Extensions> MyExtensions = new List<Extensions>() {
    new Component { 
        Name = "Component",
        Views = new List<View>() {

        }
    }
    new Module { 
        Name = "Module",
        Views = new List<View>() {

        }
    }
}

如何在View中添加属性FOO只有他的父是一个组件?

2 个答案:

答案 0 :(得分:1)

由于您的课程现在已经设置好,如果不使用某些超级hacky代码,您将无法获得该结果。相反,我认为你应该改变你的课程:

public abstract class View
{
    // ...
}

public class ModuleView : View
{ 

}

public class ComponentView : View
{
    public object Foo; //Substitute object with whatever type Foo is
}

public abstract class Extension
{
  public string Name;
  public abstract List<View> Views { get; set; }
}

public class Module : Extension 
{
    public override List<View> Views 
    {
        get
        {
            ModuleView moduleViewA = new ModuleView();
            ModuleView moduleViewB = new ModuleView();
            //Continue building whatever ModuleView objects you need...

            return new List<View>()
            {
                moduleViewA,
                moduleViewB,
                //...plus all other ModuleView objects you built
            };
        }
        set 
        {
            Views = value;
        }
    }
}

public class Component : Extension 
{
    public override List<View> Views
    {
        get
        {
            ComponentView compViewA = new ComponentView();
            ComponentView compViewB = new ComponentView();
            //Continue building whatever ComponentView objects you need...

            return new List<View>()
            {
                compViewA,
                compViewB,
                //...plus all other ComponentView objects you built
            };
        }
        set
        {
            Views = value;
        }
    }
}

这可以保证只有Component个对象才能看到字段Foo

答案 1 :(得分:0)

您的请求的目的非常模糊,但您可能拥有的一个选项 - 如果ComponentView在同一个程序集中定义 - 是为了使该属性{ {3}}。这使得该属性仅对同一程序集中的类型可见。

当然,这意味着Module(以及您想要“隐藏”Foo的任何其他类型)需要在不同的程序集中定义,否则它将可以访问财产也是如此。

Assembly1.dll

public class Extension {
      Public string Name {get; set;}
      Public List<View> Views {get; set;}
}

public class Component : Extension {
    // View.Foo is accessible here;
}

public class View {
    internal object Foo {get; set;}
}

Assembly2.dll

public class Module : Extension {
     // View.Foo is not visible here
}