【发布时间】:2014-07-29 14:44:13
【问题描述】:
我有这个函数,它在编译器中得到以下错误:cannot convert System.ValueType to T 并且 typeof(string) 块给出错误:cannot convert type 'string'到'T'
public static T ReadKey<T>(GamePrefs.Key k, T defaultValue)
{
T obj = defaultValue;
if (typeof(T) == typeof(bool))
obj = (T)(ValueType)(bool)(PlayerPrefs.GetInt(k.ToString(), !(bool)(object)defaultValue ? 0 : 1) == 1 ? true : false);
else if (typeof(T) == typeof(int))
obj = (T)(ValueType)PlayerPrefs.GetInt(k.ToString(), (int)(object)defaultValue);
else if (typeof(T) == typeof(float))
obj = (T)(ValueType)PlayerPrefs.GetFloat(k.ToString(), (float)(object)defaultValue);
else if (typeof(T) == typeof(string))
obj = (T)PlayerPrefs.GetString(k.ToString(), (string)(object)defaultValue);
else
Debug.LogError((object)string.Format("Key {0} couldn't be read because type {1} not supported.", (object)k, (object)typeof(T)));
return obj;
}
这里有什么问题?
【问题讨论】:
-
Debug.LogError((object)string.Format("Key {0} couldn't be read because type {1} not supported.", (object)k, (object)typeof(T)));Format 调用 ToString 方法。可能值得一看GetType()而不是typeof。 -
我会在类似的问题中指出 Eric Lippert 的 this answer。
-
第一个
if下的那行里面有各种wtf,可以换成obj = (bool)(PlayerPrefs.GetInt(k.ToString(), defaultValue ? 1 : 0) == 1);,不知道能不能解决你的问题。 -
说:无法将类型'T'隐式转换为'bool'(参数defaultValue)