如何测试一个类型是匿名的? [英] How To Test if a Type is Anonymous?
本文介绍了如何测试一个类型是匿名的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的方法,一个串行化对象到HTML标记。我只是想这样做,虽然如果类型不是匿名的。
I have the following method which serialises an object to a HTML tag. I only want to do this though if the type isn't Anonymous.
private void MergeTypeDataToTag(object typeData)
{
if (typeData != null)
{
Type elementType = typeData.GetType();
if (/* elementType != AnonymousType */)
{
_tag.Attributes.Add("class", elementType.Name);
}
// do some more stuff
}
}
有人能告诉我如何实现这一目标?
Can somebody show me how to achieve this?
感谢
推荐答案
来源: HTTP:// WWW。 liensberger.it/web/blog/?p=191
private static bool CheckIfAnonymousType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
// HACK: The only way to detect anonymous types right now.
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}
心连心。
编辑:结果
与扩展方法的另一个链接:<一个href=\"http://stackoverflow.com/questions/1650681/determining-whether-a-type-is-an-anonymous-type\">Determining一个类型是一个匿名类型
这篇关于如何测试一个类型是匿名的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文