该结构包括引用类型
The structure includes reference types
结构包含引用字段的方式是否正确?
喜欢下面的代码:
public class ClassA
{
//...
}
public class ClassB
{
//...
}
public struct StructAB
{
public ClassA a;
public ClassB b;
public StructAB(ClassA ca,ClassB cb)
{
this.a = ca;
this.b = cb;
}
}
是的,你可以,代码将编译。但请记住,结构是值类型。每次将结构作为参数传递时,都会创建每个成员的 shallow 副本。
如果您的结构包含引用类型,则只会复制引用(即指向成员的指针)。
因此,除非有充分的理由让您在结构内部使用引用类型,否则请避免使用它。
Typically, you use structure types to design small data-centric types
that provide little or no behavior. For example, .NET uses structure
types to represent a number (both integer and real), a Boolean value,
a Unicode character, a time instance. If you're focused on the
behavior of a type, consider defining a class. Class types have
reference semantics. That is, a variable of a class type contains a
reference to an instance of the type, not the instance itself.
结构包含引用字段的方式是否正确?
喜欢下面的代码:
public class ClassA
{
//...
}
public class ClassB
{
//...
}
public struct StructAB
{
public ClassA a;
public ClassB b;
public StructAB(ClassA ca,ClassB cb)
{
this.a = ca;
this.b = cb;
}
}
是的,你可以,代码将编译。但请记住,结构是值类型。每次将结构作为参数传递时,都会创建每个成员的 shallow 副本。 如果您的结构包含引用类型,则只会复制引用(即指向成员的指针)。 因此,除非有充分的理由让您在结构内部使用引用类型,否则请避免使用它。
Typically, you use structure types to design small data-centric types that provide little or no behavior. For example, .NET uses structure types to represent a number (both integer and real), a Boolean value, a Unicode character, a time instance. If you're focused on the behavior of a type, consider defining a class. Class types have reference semantics. That is, a variable of a class type contains a reference to an instance of the type, not the instance itself.