在类型为 T 的函数中定义为参数的变量未定义 C#
Variable defined as parameter in function of type T undefined C#
我这里有这个静态函数来决定传递的参数的类型,如果它是通用的,则调用内置的 ToString()
方法,或者调用预定义的自定义服务商来打印它的完整内容内容是否可以枚举过来。这是我目前所拥有的;
public static String ToStringDecider<T> (T value)
{
Type t = typeof(value);
if (t.IsSubclassOf (Array) || t.IsSubclassOf (IList))
return ToString_List (value);
else if (t.IsSubclassOf (IEnumerable))
return ToString_Enumerable (value);
else if (t.IsSubclassOf (IDictionary))
return ToString_Dictionary (value);
else
return value.ToString ();
}
但是,第 3 行对变量 value
的第一次引用出现语法错误,指出 "The name 'value' does not exist in the current context."
谁能解释为什么会这样?
typeof
不将变量作为参数,而是类型。
你想要:
Type t = typeof(T);
Type t = value.GetType();
请注意,您可能还需要在对辅助方法的调用中进行显式强制转换。
我这里有这个静态函数来决定传递的参数的类型,如果它是通用的,则调用内置的 ToString()
方法,或者调用预定义的自定义服务商来打印它的完整内容内容是否可以枚举过来。这是我目前所拥有的;
public static String ToStringDecider<T> (T value)
{
Type t = typeof(value);
if (t.IsSubclassOf (Array) || t.IsSubclassOf (IList))
return ToString_List (value);
else if (t.IsSubclassOf (IEnumerable))
return ToString_Enumerable (value);
else if (t.IsSubclassOf (IDictionary))
return ToString_Dictionary (value);
else
return value.ToString ();
}
但是,第 3 行对变量 value
的第一次引用出现语法错误,指出 "The name 'value' does not exist in the current context."
谁能解释为什么会这样?
typeof
不将变量作为参数,而是类型。
你想要:
Type t = typeof(T);
Type t = value.GetType();
请注意,您可能还需要在对辅助方法的调用中进行显式强制转换。