Ho il seguente metodo che serializza un object in un tag HTML. Voglio solo farlo anche se il tipo non è Anonimo.
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 } }
Qualcuno può mostrarmi come raggiungerlo?
Grazie
Da: 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; }
HTH.
MODIFICARE:
Un altro collegamento con il metodo di estensione: determinare se un tipo è di tipo anonimo
Veloce e sporco:
if(obj.GetType().Name.Contains("AnonymousType"))
Puoi semplicemente controllare se lo spazio dei nomi è nullo.
public static bool IsAnonymousType(this object instance) { if (instance==null) return false; return instance.GetType().Namespace == null; }
Bene, oggi compiier genera tipi anonimi come classi generiche sigillate. Una combinazione paradossale poiché la specializzazione di una class generica è una specie di eredità, no? Quindi è ansible verificare per questo: 1. È un tipo generico? Sì => 2) la sua definizione è sigillata e non pubblica? Sì => 3) la sua definizione ha attributo CompilerGeneratedAttribute? Immagino, se questi 3 criteri sono veri insieme, abbiamo un tipo anonimo … Beh … C’è un problema con QUALSIASI dei metodi descritti – sono aspetti di utilizzo che potrebbero cambiare nelle prossime versioni di .NET e sarà così fino a quando Microsoft aggiungerà la proprietà booleana IsAnonymous alla class Type. Spero che accada prima che moriamo tutti … Fino a quel giorno, può essere controllato in questo modo:
using System.Runtime.CompilerServices; using System.Reflection; public static class AnonymousTypesSupport { public static bool IsAnonymous(this Type type) { if (type.IsGenericType) { var d = type.GetGenericTypeDefinition(); if (d.IsClass && d.IsSealed && d.Attributes.HasFlag(TypeAttributes.NotPublic)) { var attributes = d.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false); if (attributes != null && attributes.Length > 0) { //WOW! We have an anonymous type!!! return true; } } } return false; } public static bool IsAnonymousType(this T instance) { return IsAnonymous(instance.GetType()); } }
Cerca CompilerGeneratedAttribute
e DebuggerDisplayAttribute.Type
ecco il codice generato dal compilatore per un tipo anomalo
[CompilerGenerated, DebuggerDisplay(@"\{ a = {a} }", Type="")] internal sealed class <>f__AnonymousType0<j__TPar> { ... }