如何从隐式操作符重载代码中访问对象的字段?



我有一个类,其中包含bool, int和float值(加上所选类型和名称)。

using UnityEngine;
using System.Collections;
[System.Serializable]
public class AnimXVariable {
        public string name = "variable";
        public enum VariableType { Bool, Int, Float };
        public VariableType type = VariableType.Bool;
        public bool boolVal = false;
        public int intVal = 0;
        public float floatVal = 0f;
        public AnimXVariable() {
                type = VariableType.Bool;
        }
        public AnimXVariable(VariableType newType) {
                type = newType;
        }
        public AnimXVariable(string newName, VariableType newType, bool val) {
                name = newName;
                type = newType;
                boolVal = val;
        }
        public AnimXVariable(string newName, VariableType newType, float val) {
                name = newName;
                type = newType;
                floatVal = val;
        }
        public AnimXVariable(string newName, VariableType newType, int val) {
                name = newName;
                type = newType;
                intVal = val;
        }       
        public AnimXVariable(bool newValue) {
                if(type == VariableType.Bool) boolVal = newValue;
        }
        public AnimXVariable(float newValue) {
                if(type == VariableType.Float) floatVal = newValue;
        }
        public AnimXVariable(int newValue) {
                if(type == VariableType.Int) intVal = newValue;
        }
        public static implicit operator AnimXVariable(bool val) {
                return new AnimXVariable(name, type, val); //The problem is I can't access the non-static members. If I simply return new AnimXVariable(val); it does work, but the name is gone...
        }
}

我正在尝试使用隐式操作符使以下工作:

AnimXVariable b = new AnimXVariable("jump", VariableType.Bool, false);
b = true;

问题是我不能访问非静态成员。如果我只是这么做返回新的AnimXVariable(val);确实有用,但名字没了……是否有任何方法可以在隐式操作符代码中获取有关对象的信息以使此工作?

问题是我不能访问非静态成员。

不,你不能——没有上下文。你只是想把bool的值转换成AnimXVariable。这就是所有输入数据。你谈论"对象"——那里没有对象。

用另一种方式说——使用隐式操作符,应该能够写:

AnimXVariable b = true;

那是什么意思?会叫什么名字呢?

我强烈建议您重新考虑在这里使用隐式转换操作符。听起来你可能想要一个像

这样的实例方法:
public AnimXVariable WithValue(bool newValue)
{
    return new AnimXVariable(name, type, newValue);
}

最新更新