Tag: typechecking

检查方法与给定Delegate的兼容性?

在C#代码中,如何检查给定方法是否可以由特定委托类型表示? 我首先根据我的类型知识尝试了一些东西: // The delegate to test against. void TargetDelegate(string msg); // and… var methodInfo = Type.GetMethod(..); // obtain the MethodInfo instance. // try to test it typeof(TargetDelegate).IsAssignableFrom(methodInfo.GetType()); 但这只涉及类型而不是方法 – 它总是错误的。 我倾向于相信答案在于Delegate类型,但我现在只是在FCL游荡。 任何帮助,将不胜感激。

enum 是IEnumerable 在generics方法中返回true

这是此问题的后续内容: 对通用枚举集合应用的Cast .Cast 会导致无效的强制转换exception enum Gender { Male, Female } Gender g = Gender.Male; bool b = g is int; // false, alright no issues b = new[] { g } is IEnumerable; // false, alright no issues b = Is(g); //false, alright no issues b = Is<Gender[], IEnumerable>(new[] { g }); // true, why […]

如何检测对象是否为通用集合,以及它包含哪些类型?

我有一个字符串序列化实用程序,它接受(几乎)任何类型的变量并将其转换为字符串。 因此,例如,根据我的惯例,整数值123将被序列化为“i:3:123”(i =整数; 3 =字符串的长度; 123 =值)。 该实用程序处理所有原始类型,以及一些非generics集合,如ArrayLists和Hashtables。 界面是这种forms public static string StringSerialize(object o) {} 在内部我检测对象是什么类型并相应地序列化它。 现在我想升级我的实用程序来处理generics集合。 有趣的是,我找不到一个合适的函数来检测对象是一个generics集合,它包含哪些类型 – 我需要哪些信息才能正确序列化。 到目前为止,我一直在使用表格的编码 if (o is int) {// do something} 但这似乎不适用于generics。 您有什么推荐的吗? 编辑:感谢Lucero ,我已经接近答案了,但我仍然坚持这个小小的语法难题: if (t.IsGenericType) { if (typeof(List) == t.GetGenericTypeDefinition()) { Type lt = t.GetGenericArguments()[0]; List x = (List)o; stringifyList(x); } } 此代码无法编译,因为“ lt ”不允许作为List对象的参数。 为什么不? […]