如何测试一个类型是否是匿名的? [英] 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.HasFlag(TypeAttributes.NotPublic);
}
另一个带有扩展方法的链接:确定一个类型是否是匿名类型一个>
这篇关于如何测试一个类型是否是匿名的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文