会员在C#中传递?

时间:2017-02-03 10:46:18

标签: c# syntactic-sugar

Go有一个nice feature,嵌套结构的成员可以通过其父结构自动访问:

implicit

在C#中是否可以,例如使用struct B { public int x; } struct A { public B b; } var a = new A(); a.b.x = 1; // How it usually works a.x = 1; // How Go works, assuming x is unambiguous 强制转换?

function SomeConstructor() {}
SomeConstructor.prototype.someMethod = function() {}
var someItem = new SomeConstructor()
someItem.someMethod()

2 个答案:

答案 0 :(得分:0)

C#中没有这样的概念。您可以自己添加这些属性,但对于看到您的代码的其他开发人员来说,这将非常混乱。

struct B
{
    public int x;
}

struct A
{
    public B b;
    public int x {
        get { return b.x; }
        set { b.x = value; }
    }
}

}

var a = new A();

a.b.x = 1;
a.x = 1;

但是,如果您切换到类而不是结构 - 使用inheritance可以有类似的行为:

class B
{
    public int x;
}

class A : B
{
}

var a = new A();
a.x = 1;

答案 1 :(得分:0)

嵌入的Golang结构可以看作是一种继承"。如果要在C#中模拟此行为,则应使用类而不是struct(here if you want know the difference between struct and class) 像这样:

public class A {
    public int X {get; set;}
}
public class B : A{
    B : base() {}
}
...
var a = new B();
a.X = 24;