2

当我第一次看到 C# 中的值类型时,我首先想到的是“哇,多么棒的优化”,第二件事是,“我们真的需要一种新的语言结构吗?我们不能用注解来代替吗? ”。

这个想法是,给定一个类,我们将像往常一样使用它

class A {int i;}
class B {
    A m_a;
    int F(A a) {m_a = a;}
}

一时兴起,我们会A变成

[ValueType]
class A {int i;int j;}

并且编译器会自动将类转换B

class B {
#region A
    int A_i;
    int A_j;
#endregion
int F(/*A param*/int i,int j) {
#region A_assign
    A_i = i;
    A_j = j;
#endregion
}

请记住,如果编译器不希望优化某些实例 - 它不必这样做。无论哪种方式都可以。

模板可能会出现问题,

int f<T>() {
    T t; // how much stack should I allocate
}

但我不确定它是否比目前的情况更糟。我实际上不确定现在会发生什么(f<struct_of_100_bytes>与功能不同f<int>?)。

4

1 回答 1

2

Now imagine inheritance. Or arrays. Or arguments. Or generics. Or implementing an interface. Or assigning to object/dynamic.

And keep in mind that the runtime supports multiple compilers.

Having a specific keyword (struct) rather than an attribute is not really a big change (indeed, in terms of the CLI everything is called a class), but the overall situation is much more complex than your example.

Basically, struct does pretty-much everything you mention, and works in all the scenarios listed. Since it generally (for locals) uses the stack, it already behaves much like you describe.

Re the "separate function" question; firstly, generics are not "templates" (it is runtime vs compile-time). But generics get a JIT per value-type, and a single JIT per reference-type (because indeed: the stack layout changes.

于 2011-09-11T09:00:08.610 回答