C#中的成员传递?
Go具有一个可通过其父结构自动访问嵌套结构成员的功能:C#中的成员传递?,c#,syntactic-sugar,C#,Syntactic Sugar,Go具有一个可通过其父结构自动访问嵌套结构成员的功能: // Server exposes all the methods that Logger has type Server struct { Host string Port int *log.Logger } // initialize the embedded type the usual way server := &Server{"localhost", 80, log.New(...)} //
// Server exposes all the methods that Logger has
type Server struct {
Host string
Port int
*log.Logger
}
// initialize the embedded type the usual way
server := &Server{"localhost", 80, log.New(...)}
// methods implemented on the embedded struct are passed through
server.Log(...) // calls server.Logger.Log(...)
// the field name of the embedded type is its type name (in this case Logger)
var logger *log.Logger = server.Logger
在C#中是否也可以这样,例如使用implicit
cast
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
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;
但是,如果您切换到类而不是结构,则可以使用以下方法获得类似的行为:
嵌入的Golang结构可以看作是一种“继承”。如果要在C#中模拟这种行为,应该使用类而不是struct()。
大概是这样的:
public class A {
public int X {get; set;}
}
public class B : A{
B : base() {}
}
...
var a = new B();
a.X = 24;
不,在C#中没有这样的。你可以添加你自己的属性来委托,这是真的,但我更愿意在C#中使用合成风格。例如,mixin使用这种语法糖就更好了。
public class A {
public int X {get; set;}
}
public class B : A{
B : base() {}
}
...
var a = new B();
a.X = 24;