本文介绍了问题的结构和性质在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;
    }
}

智能感知识别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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:32