This question already has answers here:
Anonymous Types - Are there any distingushing characteristics?
(3个答案)
7年前关闭。
我有以下将对象序列化为HTML标签的方法。但是,如果类型不是Anonymous,我只想这样做。
有人可以告诉我如何实现这一目标吗?
谢谢
编辑:
扩展方法的另一个链接:Determining whether a Type is an Anonymous Type
(3个答案)
7年前关闭。
我有以下将对象序列化为HTML标签的方法。但是,如果类型不是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
}
}
有人可以告诉我如何实现这一目标吗?
谢谢
最佳答案
从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);
}
编辑:
扩展方法的另一个链接:Determining whether a Type is an Anonymous Type
关于c# - 如何测试类型是否为匿名? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2483023/
10-10 04:53