【问题标题】:Variable defined as parameter in function of type T undefined C#变量定义为类型 T 未定义 C# 函数中的参数
【发布时间】:2015-04-12 14:35:31
【问题描述】:

我这里有一个静态函数,它决定传递参数的类型,如果它是泛型的,则在其上调用内置的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." 任何人都可以解释为什么会这样吗?

【问题讨论】:

  • 你试过value.GetType() 吗?
  • 为什么typeof() 不够用?
  • 不应该是 typeof(T) 吗?
  • Type t = T; 替换该行似乎不会给出任何语法错误。它会完成同样的事情吗?
  • 你好像受到c语言的影响;)

标签: c# list types tostring


【解决方案1】:

typeof 不以变量为参数,而是以类型为参数。

你想要:

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

请注意,您可能还需要在对辅助方法的调用中显式强制转换。

【讨论】:

  • 等待;如果typeof(Array) 返回Arraytype,那么Array 本身是什么类型的对象?这一切都非常令人困惑。
  • @Maurdekye typeof 是 C# 中的关键字,它不是被调用的方法,a'la object.GetType()。编译器将 typeof 转换为特定的 MSIL 操作码,并在 Type.GetTypeFromHandle 上调用(有关详细信息,请参阅 stackoverflow.com/questions/3145930/how-does-typeof-work)。
猜你喜欢
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 2016-06-14
相关资源
最近更新 更多