2013-10-29 52 views
1
public class Foo 
{ 
Bar Field{get;set;} 
} 

    public class Bar 
    { 
    public int Value{get;set}; 
    public int Value2{get;set;} 
    } 

是否有可能做这样的事情,在C#:发布类领域的另一个类领域

Foo a = new Foo(); 
a.Value = 5; 
a.Value2 = 8; 

在换句话说,有没有可能发布酒吧类的领域,如果酒吧是一个基类?

+0

你想组合工作像继承?你必须在Foo中滚动你自己的属性。 – Vivek

回答

0

不是直接的,但可以将属性添加到“外层”类以明确地公开它们。

public class Foo 
{ 
    Bar Field{get;set;} 

    public int Value{get { return Field.Value;} } 
    public int Value2{get { return Field.Value2;} } 
} 

public class Bar 
{ 
    public int Value{get;set}; 
    public int Value2{get;set;} 
} 

但是,这当然不是很方便。如果你真的想更自动地得到类似这样的东西,你可以用dynamic和自定义的TypeDescriptors来实现,但这反过来会阻止编译时类型和成员验证。我不建议直到你确实需要。

+0

OP使用'set'访问器以及 –

+0

我相信他的智能可以找到该模式并相应地应用。 – quetzalcoatl

+0

这就是我想要实现的,但我想自动拥有它 – MistyK

1

既然你有Bar类型属性在你的类Foo,你有组成。你可以通过这样的属性访问字段:

Foo a = new Foo(); 
a.Field.Value = 1; 
a.Field.Value2 = 2; 

但是你必须要修改当前的代码:

public class Foo 
{ 
    public Bar Field { get; set; } //make the property public 
} 

public class Bar 
{ 
    public int Value { get; set; } 
    public int Value2 { get; set; } 
} 

另一种选择是继承BarFoo,如:

public class Foo : Bar 
{ 
    public int FooID { get; set; } 
} 

然后你可以直接访问Bar的领域:

Foo a = new Foo(); 
a.Value = 1; 
a.Value2 = 2; 
+0

或者'public bar field {get;私人设置; }'。 – Dennis