代码之家  ›  专栏  ›  技术社区  ›  FutureCake

为什么我可以在只读变量中设置字段的值?c

  •  0
  • FutureCake  · 技术社区  · 5 年前

    我编写了以下代码:

    public class AppearanceDefinition<VertexInfo> where VertexInfo : struct
    {
        public readonly ShaderProperty<bool> HasBorder; // READONLY VARIABLE
        public readonly ShaderProperty<float> BorderSize;
    
        internal readonly Shader[] Shaders;
    
        private readonly string VertexShaderCode;
        private readonly string FragmentShaderCode;
    
        public AppearanceDefinition(string vertexCode, string fragmentCode)
        {
            this.VertexShaderCode = vertexCode;
            this.FragmentShaderCode = fragmentCode;
    
            HasBorder = new ShaderProperty<bool>("HasBorder", ResourceKind.UniformBuffer, ShaderStages.Fragment, 0);
            BorderSize = new ShaderProperty<float>("BorderSize", ResourceKind.UniformBuffer, ShaderStages.Fragment, 0);
        }
    }
    
    public class ShaderProperty<T> where T : struct
    {
        public readonly string Name;
        public readonly ResourceKind InternalDataType;
        public readonly ShaderStages ShaderStage;
        public readonly uint GroupId;
    
        private T _value;
        public T Value 
        { 
            get 
            {
                return _value;
            }
            set 
            {
                _value = value;
                // requires buffer update. 
            }
        }
    
        public ShaderProperty(string name, ResourceKind internalDataType, ShaderStages stage, uint group) 
        {
            this.Name = name;
            this.InternalDataType = internalDataType;
            this.ShaderStage = stage;
            this.GroupId = group;
            this._value = default(T);
        }
    }
    

    我这样使用它:

    class Program
    {
        static AppearanceDefinition<bool> test;
    
        static void Main(string[] args)
        {
            test = new AppearanceDefinition<bool>("", "");
            test.HasBorder.Value = true;
        }
    }
    

    这工作得很好,价值 HasBorder 更改从 false true .
    这很棒,因为我不想让人们重新分配价值 HasBorder 但我确实希望人们改变 HasBorder.Value 。但我在某种程度上可以更改只读变量,这感觉很奇怪。
    有人能解释一下为什么这是可能的,是否有更好的方法?

    0 回复  |  直到 5 年前
        1
  •  2
  •   YankTHEcode    5 年前

    您可以更改HasBorder。值,但您无法更改HasBorder,因为HasBorder是只读的。尝试将HasBorder等同于其他东西,它就会失败。

    重要的是要记住,当只读数据成员是引用类型(即类的实例,而不是结构或基础数据类型)时,引用是常量,但它指向的实例不是常量。因此,只读实例的内部状态可以更改,并且可以更改