मेरे आवेदन में मुझे रनटाइम के दौरान गुण बनाने/हटाने के लिए ExpandoObject का उपयोग करना होगा; हालांकि, मुझे किसी फंक्शन के लौटे ExpandoObject को संबंधित ऑब्जेक्ट/क्लास में मैप करना होगा।रिकर्सिवली मैपिंग ExpandoObject
- के रूप में माना जाता यह रिकर्सिवली ExpandoObject के भीतर वस्तुओं को मैप नहीं है: तो मैं एक छोटे से मैपर कि काम करता है के साथ लेकिन 3 समस्याओं के साथ आया है।
- जब मैं int को nullable में मैप करने का प्रयास करता हूं तो यह एक प्रकार मेल नहीं खाएगा क्योंकि मुझे इसका पता लगाने और सही तरीके से कास्ट करने का कोई तरीका नहीं मिल रहा है।
- फ़ील्ड्स को
public string Property;
मैप नहीं किया जा सकता है।
कोड:
I- कार्यान्वयन:
public static class Mapper<T> where T : class
{
#region Properties
private static readonly Dictionary<string, PropertyInfo> PropertyMap;
#endregion
#region Ctor
static Mapper() { PropertyMap = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToDictionary(p => p.Name.ToLower(), p => p); }
#endregion
#region Methods
public static void Map(ExpandoObject source, T destination)
{
if (source == null)
throw new ArgumentNullException("source");
if (destination == null)
throw new ArgumentNullException("destination");
foreach (var kv in source)
{
PropertyInfo p;
if (PropertyMap.TryGetValue(kv.Key.ToLower(), out p))
{
Type propType = p.PropertyType;
if (kv.Value == null)
{
if (!propType.IsByRef && propType.Name != "Nullable`1")
{
throw new ArgumentException("not nullable");
}
}
else if (kv.Value.GetType() != propType)
{
throw new ArgumentException("type mismatch");
}
p.SetValue(destination, kv.Value, null);
}
}
}
#endregion
}
द्वितीय: उपयोग:
public static void Main()
{
Class c = new Class();
dynamic o = new ExpandoObject();
o.Name = "Carl";
o.Level = 7;
o.Inner = new InnerClass
{
Name = "Inner Carl",
Level = 10
};
Mapper<Class>.Map(o, c);
Console.Read();
}
internal class Class
{
public string Name { get; set; }
public int? Level { get; set; }
public InnerClass Inner { get; set; }
public string Property;
}
internal class InnerClass
{
public string Name { get; set; }
public int? Level { get; set; }
}
किसी भी सवाल का जवाब ... –