0

这可能很简单,但我是 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 只有他的父级是一个组件?

4

2 回答 2

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对象才能看到 field Foo

于 2013-08-25T18:22:55.117 回答
0

您请求的目的非常模糊,但您可能拥有的一个选项(如果Component在与相同的程序集中定义)View是创建该属性internal。这使得该属性仅对同一程序集中的类型可见。

当然,这意味着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
}
于 2013-08-25T21:31:36.587 回答