1

I have a class that holds a bool, int and float value (plus the selected type and a name).

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...
        }

}

I'm trying to use an implicit operator to make the following work:

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

The problem is I can't access the non-static members. If I simply do return new AnimXVariable(val); it does work, but the name is gone... Is there any way to get information about the object inside the implicit operator code to make this work?

4

1 回答 1

6

问题是我无法访问非静态成员。

不,你不能——没有上下文。您只是想将bool值转换为AnimXVariable. 这就是所有的输入数据。您谈论“对象”-没有对象。

换句话说 - 使用隐式运算符,您应该能够编写:

AnimXVariable b = true;

那意味着什么?名字会是什么?

我强烈建议您重新考虑尝试在这里使用隐式转换运算符。听起来您可能想要一个类似的实例方法:

public AnimXVariable WithValue(bool newValue)
{
    return new AnimXVariable(name, type, newValue);
}
于 2013-01-03T09:57:00.717 回答