在 java 中,我们可以从函数本身的抽象 class 派生出 class。我们也可以为 C# 做吗?
In java we can derived the class from abstract class in function itself. Can we do for C# also?
在Java中,我们可以从函数本身的抽象class中导出class。
我们可以为 C# 做同样的事情吗?
public class A {
public final static A d = new A();
protected abstract class M {
public int getValue() {
return 0;
}
}
protected static M[] c = null;
public final static void Foo() {
if (c == null) {
M[] temp = new M[] {
d.new M() {
public int getValue() {
return 1;
}
},
d.new M() {
public int getValue() {
return 2;
}
},
d.new M() {
public int getValue() {
return 3;
}
}
};
c = temp;
}
}
}
不,在 C# 中没有等效的匿名内部 类。
通常对于单一方法抽象 类 或接口,您会在 C# 中使用委托,并且经常使用 lambda 表达式来创建实例。
所以与您的代码相似的东西是:
public class A
{
public delegate int Int32Func();
private static Int32Func[] functions;
// Note: this is *not* thread safe...
public static void Foo() {
if (functions == null) {
functions = new Int32Func[]
{
() => 1,
() => 2,
() => 3
};
}
}
}
... 除了我会使用 Func<int>
而不是声明我自己的委托类型。
只是为了添加对 Jon Skeet 回答的引用。 C# 中的匿名类型只能定义 public 个只读属性。请参阅 C# 编程指南的摘录(可在此处找到 https://msdn.microsoft.com/en-us/library/bb397696.aspx):
Anonymous types contain one or more public read-only properties. No
other kinds of class members, such as methods or events, are valid.
The expression that is used to initialize a property cannot be null,
an anonymous function, or a pointer type.
简短的回答(正如 Jon 已经说过的那样)是匿名类型不能有方法,但在大多数情况下您可以使用匿名函数或委托来获得相同的行为。
在Java中,我们可以从函数本身的抽象class中导出class。
我们可以为 C# 做同样的事情吗?
public class A {
public final static A d = new A();
protected abstract class M {
public int getValue() {
return 0;
}
}
protected static M[] c = null;
public final static void Foo() {
if (c == null) {
M[] temp = new M[] {
d.new M() {
public int getValue() {
return 1;
}
},
d.new M() {
public int getValue() {
return 2;
}
},
d.new M() {
public int getValue() {
return 3;
}
}
};
c = temp;
}
}
}
不,在 C# 中没有等效的匿名内部 类。
通常对于单一方法抽象 类 或接口,您会在 C# 中使用委托,并且经常使用 lambda 表达式来创建实例。
所以与您的代码相似的东西是:
public class A
{
public delegate int Int32Func();
private static Int32Func[] functions;
// Note: this is *not* thread safe...
public static void Foo() {
if (functions == null) {
functions = new Int32Func[]
{
() => 1,
() => 2,
() => 3
};
}
}
}
... 除了我会使用 Func<int>
而不是声明我自己的委托类型。
只是为了添加对 Jon Skeet 回答的引用。 C# 中的匿名类型只能定义 public 个只读属性。请参阅 C# 编程指南的摘录(可在此处找到 https://msdn.microsoft.com/en-us/library/bb397696.aspx):
Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.
简短的回答(正如 Jon 已经说过的那样)是匿名类型不能有方法,但在大多数情况下您可以使用匿名函数或委托来获得相同的行为。