col*_*00r 1 c# unity-game-engine implicit-conversion
我有一个包含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...
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用隐式运算符来完成以下工作:
AnimXVariable b = new AnimXVariable("jump", VariableType.Bool, false);
b = true;
Run Code Online (Sandbox Code Playgroud)
问题是我无法访问非静态成员.如果我只是返回新的AnimXVariable(val); 它确实有效,但名称已经消失......有没有办法在隐式运算符代码中获取有关对象的信息以使其工作?
问题是我无法访问非静态成员.
不,你将无法 - 没有背景.您只是想将bool值转换为AnimXVariable.这就是所有的输入数据.请您谈一下"对象" -有是没有对象.
换句话说 - 使用隐式运算符,您应该能够编写:
AnimXVariable b = true;
Run Code Online (Sandbox Code Playgroud)
那是什么意思?这个名字是什么?
我强烈建议你重新考虑尝试在这里使用隐式转换运算符.听起来你可能想要一个类似的实例方法:
public AnimXVariable WithValue(bool newValue)
{
return new AnimXVariable(name, type, newValue);
}
Run Code Online (Sandbox Code Playgroud)