本文介绍了c#中结构和属性的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个文件中我定义了一个公共结构
in a file I defined a public struct
public struct mystruct
{
public Double struct1;
public Decimal struct2;
}
在另一个我尝试这样做:
In another I tried to do this:
class Test
{
mystruct my_va;
public mystruct my_va
{
get { return my_va; }
set { my_va = value; }
}
public Test()
{
my_va.struct1 = 10;
}
}
Intellisense 识别 My_va.struct1 但编译器说
Intellisense recognizes My_va.struct1 but compiler says
错误 1 无法修改返回值'TEST.mystruct' 因为它不是变量
如何更正语法?
推荐答案
强烈建议避免使用可变结构.他们表现出各种令人惊讶的行为.
It is highly recommended to avoid mutable structs. They exhibit all sorts of surprising behaviour.
解决方案:使您的结构不可变.
Solution: Make your struct immutable.
public struct MyStruct
{
public readonly double Value1;
public readonly decimal Value2;
public MyStruct(double value1, decimal value2)
{
this.Value1 = value1;
this.Value2 = value2;
}
}
用法:
class Test
{
private MyStruct myStruct;
public Test()
{
myStruct = new MyStruct(10, 42);
}
public MyStruct MyStruct
{
get { return myStruct; }
set { myStruct = value; }
}
}
这篇关于c#中结构和属性的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!