变量定义为类型T函数中的参数未定义C#

时间:2015-02-12 01:16:28

标签: c# list types tostring

我在这里有这个静态函数来决定传递参数的类型,如果它是通用的,则调用内置的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."有人可以解释为什么会发生这种情况吗?

1 个答案:

答案 0 :(得分:2)

typeof不接受变量作为参数,而是输入。

你想要:

Type t = typeof(T);
Type t = value.GetType();

请注意,您还可能需要显式调用辅助方法。