Come dinamizzare la nuova classe anonima?


95

In C # 3.0 è possibile creare una classe anonima con la sintassi seguente

var o1 = new { Id = 1, Name = "Foo" };

C'è un modo per creare dinamicamente queste classi anonime in una variabile?


Esempio:

var o1 = new { Id = 1, Name = "Foo" };
var o2 = new { SQ = 2, Birth = DateTime.Now };

Esempio di creazione dinamica:

var o1 = DynamicNewAnonymous(new NameValuePair("Id", 1), new NameValuePair("Name", "Foo"));
var o2 = DynamicNewAnonymous(new NameValuePair("SQ", 2), new NameValuePair("Birth", 
DateTime.Now));

Perché devo fare:

dynamic o1 = new ExpandObject(); 
o1."ID" = 1;    <--"ID" is dynamic name
o1."Name" = "Foo";  <--"Name" is dynamic name

E Scene1:

void ShowPropertiesValue(object o)
{
  Type oType = o.GetType();
  foreach(var pi in oType.GetProperties())
  {
    Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
  }
}

se chiamo:

dynamic o1 = new ExpandObject();
o1.Name = "123";
ShowPropertiesValue(o1);

Non può mostrare il risultato:

Name = 123

E anche come convertire ExpandoObject in AnonymouseType?

Type type = o1.GetType();
type.GetProperties();   <--I hope it can get all property of o1

Infine, modifico il metodo ShowPropertiesValue ()

void ShowPropertiesValue(object o)
{
  if( o is static object ) <--How to check it is dynamic or static object?
  {
    Type oType = o.GetType();
    foreach(var pi in oType.GetProperties())
    {
      Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
    }
  }
  else if( o is dynamic object )  <--How to check it is dynamic or static object?
  {
    foreach(var pi in ??? )  <--How to get common dynamic object's properties info ?
    {
      Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
    } 
  }
}

Come implementare il metodo DynamicNewAnonymous o come modificare ShowPropertiesValue ()?

Le mie motivazioni sono:

dynamic o1 = new MyDynamic();
o1.Name = "abc";
Type o1Type = o1.GetType();
var props = o1Type.GetProperties(); <--I hope can get the Name Property

Se posso agganciare il metodo GetType di dynamicObject e Compel convertirli in un tipo fortemente tipizzato. Il codice Seamless di cui sopra può funzionare correttamente.


@Vlad: ammetto di essere un po 'poco chiaro sulle motivazioni.
Steven Sudit

@VladLazarenko Penso che tu abbia ragione :-)
oberfreak

Per favore dicci cosa vuoi fare e perché questa è la tua soluzione selezionata.
oberfreak

ExpandoObject, non ExpandObject (aggiunta "o").
N0thing

@StevenSudit Questo articolo può aiutarti a scoprire la tua motivazione nell'usare l'uno o l'altro: blogs.msdn.com/b/csharpfaq/archive/2010/01/25/…
juagicre

Risposte:


75

I tipi anonimi sono solo tipi regolari dichiarati implicitamente. Hanno poco a che fare con dynamic.

Ora, se dovessi usare un ExpandoObject e fare riferimento ad esso tramite una dynamicvariabile, potresti aggiungere o rimuovere i campi al volo.

modificare

Certo che puoi: trasmettilo a IDictionary<string, object>. Quindi puoi usare l'indicizzatore.

Usi la stessa tecnica di casting per iterare sui campi:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<string, object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33

Il codice sopra e altro può essere trovato facendo clic su quel collegamento.


1
Ma ExpandoObject non può farlo:dynamic o1 = new ExpandObject(); o1."ID" = 1; o1."Name" = "Foo";
Flash

Ma non può nemmeno farlo: Digitare o1Type = o1.GetType (); var props = o1Type.GetProperties (); puntelli è vuoto
Flash

3
Tutto quello che stai facendo è dire che le proprietà dinamiche non sono identiche alle proprietà fortemente tipizzate. Questo è banalmente vero.
Steven Sudit

4
stackoverflow.com/a/4024786/998793 mostra come farlo gettando a un dizionario generico: ((IDictionary<string, object>)o1).Add("Name", "Foo");. È quindi possibile accedere a aso1.Name
rogersillito

15

Puoi creare un ExpandoObject in questo modo:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

E dopo averlo trasmesso a dinamico, quei valori appariranno come proprietà:

dynamic d = expando;
Console.WriteLine(d.Name);

Tuttavia, non sono proprietà effettive e non è possibile accedervi utilizzando Reflection. Quindi la seguente istruzione restituirà un valore nullo:

d.GetType().GetProperty("Name") 

1

Ovviamente è possibile creare classi dinamiche utilizzando la classe ExpandoObject molto interessante. Ma di recente ho lavorato al progetto e ho riscontrato che Expando Object non è serealizzato nello stesso formato su xml di una semplice classe anonima, è stato un peccato = (, ecco perché ho deciso di creare la mia classe e condividerla con te. riflessione e direttiva dinamica, costruisce Assembly, Classe e Istanza in modo veramente dinamico. Puoi aggiungere, rimuovere e modificare le proprietà incluse nella tua classe al volo Eccolo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using static YourNamespace.DynamicTypeBuilderTest;

namespace YourNamespace
{

    /// This class builds Dynamic Anonymous Classes

    public class DynamicTypeBuilderTest
    {    
        ///   
        /// Create instance based on any Source class as example based on PersonalData
        ///
        public static object CreateAnonymousDynamicInstance(PersonalData personalData, Type dynamicType, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            var obj = Activator.CreateInstance(dynamicType);

            var propInfos = dynamicType.GetProperties();

            classDescriptionList.ForEach(x => SetValueToProperty(obj, propInfos, personalData, x));

            return obj;
        }

        private static void SetValueToProperty(object obj, PropertyInfo[] propInfos, PersonalData aisMessage, ClassDescriptorKeyValue description)
        {
            propInfos.SingleOrDefault(x => x.Name == description.Name)?.SetValue(obj, description.ValueGetter(aisMessage), null);
        }

        public static dynamic CreateAnonymousDynamicType(string entityName, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            AssemblyName asmName = new AssemblyName();
            asmName.Name = $"{entityName}Assembly";
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule($"{asmName.Name}Module");

            TypeBuilder typeBuilder = moduleBuilder.DefineType($"{entityName}Dynamic", TypeAttributes.Public);

            classDescriptionList.ForEach(x => CreateDynamicProperty(typeBuilder, x));

            return typeBuilder.CreateTypeInfo().AsType();
        }

        private static void CreateDynamicProperty(TypeBuilder typeBuilder, ClassDescriptorKeyValue description)
        {
            CreateDynamicProperty(typeBuilder, description.Name, description.Type);
        }

        ///
        ///Creation Dynamic property (from MSDN) with some Magic
        ///
        public static void CreateDynamicProperty(TypeBuilder typeBuilder, string name, Type propType)
        {
            FieldBuilder fieldBuider = typeBuilder.DefineField($"{name.ToLower()}Field",
                                                            propType,
                                                            FieldAttributes.Private);

            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name,
                                                             PropertyAttributes.HasDefault,
                                                             propType,
                                                             null);

            MethodAttributes getSetAttr =
                MethodAttributes.Public | MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig;

            MethodBuilder methodGetBuilder =
                typeBuilder.DefineMethod($"get_{name}",
                                           getSetAttr,
                                           propType,
                                           Type.EmptyTypes);

            ILGenerator methodGetIL = methodGetBuilder.GetILGenerator();

            methodGetIL.Emit(OpCodes.Ldarg_0);
            methodGetIL.Emit(OpCodes.Ldfld, fieldBuider);
            methodGetIL.Emit(OpCodes.Ret);

            MethodBuilder methodSetBuilder =
                typeBuilder.DefineMethod($"set_{name}",
                                           getSetAttr,
                                           null,
                                           new Type[] { propType });

            ILGenerator methodSetIL = methodSetBuilder.GetILGenerator();

            methodSetIL.Emit(OpCodes.Ldarg_0);
            methodSetIL.Emit(OpCodes.Ldarg_1);
            methodSetIL.Emit(OpCodes.Stfld, fieldBuider);
            methodSetIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(methodGetBuilder);
            propertyBuilder.SetSetMethod(methodSetBuilder);

        }

        public class ClassDescriptorKeyValue
        {
            public ClassDescriptorKeyValue(string name, Type type, Func<PersonalData, object> valueGetter)
            {
                Name = name;
                ValueGetter = valueGetter;
                Type = type;
            }

            public string Name;
            public Type Type;
            public Func<PersonalData, object> ValueGetter;
        }

        ///
        ///Your Custom class description based on any source class for example
        /// PersonalData
        public static IEnumerable<ClassDescriptorKeyValue> GetAnonymousClassDescription(bool includeAddress, bool includeFacebook)
        {
            yield return new ClassDescriptorKeyValue("Id", typeof(string), x => x.Id);
            yield return new ClassDescriptorKeyValue("Name", typeof(string), x => x.FirstName);
            yield return new ClassDescriptorKeyValue("Surname", typeof(string), x => x.LastName);
            yield return new ClassDescriptorKeyValue("Country", typeof(string), x => x.Country);
            yield return new ClassDescriptorKeyValue("Age", typeof(int?), x => x.Age);
            yield return new ClassDescriptorKeyValue("IsChild", typeof(bool), x => x.Age < 21);

            if (includeAddress)
                yield return new ClassDescriptorKeyValue("Address", typeof(string), x => x?.Contacts["Address"]);
            if (includeFacebook)
                yield return new ClassDescriptorKeyValue("Facebook", typeof(string), x => x?.Contacts["Facebook"]);
        }

        ///
        ///Source Data Class for example
        /// of cause you can use any other class
        public class PersonalData
        { 
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Country { get; set; }
            public int Age { get; set; }

            public Dictionary<string, string> Contacts { get; set; }
        }

    }
}

È anche molto semplice usare DynamicTypeBuilder, devi solo inserire poche righe come questa:

    public class ExampleOfUse
    {
        private readonly bool includeAddress;
        private readonly bool includeFacebook;
        private readonly dynamic dynamicType;
        private readonly List<ClassDescriptorKeyValue> classDiscriptionList;
        public ExampleOfUse(bool includeAddress = false, bool includeFacebook = false)
        {
            this.includeAddress = includeAddress;
            this.includeFacebook = includeFacebook;
            this.classDiscriptionList = DynamicTypeBuilderTest.GetAnonymousClassDescription(includeAddress, includeFacebook).ToList();
            this.dynamicType = DynamicTypeBuilderTest.CreateAnonymousDynamicType("VeryPrivateData", this.classDiscriptionList);
        }

        public object Map(PersonalData privateInfo)
        {
            object dynamicObject = DynamicTypeBuilderTest.CreateAnonymousDynamicInstance(privateInfo, this.dynamicType, classDiscriptionList);

            return dynamicObject;
        }

    }

Spero che questo frammento di codice aiuti qualcuno =) Divertiti!

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.