C# ExpandoObject
▌Introduction
We will learn how to add a dynamic
property or method to an ExpandoObject
object.
▌Environment
▋Visual Studio 2017 community
▋dotnet core 2.1.2
▌Implement
▋Sample codes
static void Main(string[] args)
{
Console.WriteLine("Sample for ExpandoObject");
//New object
object myObj = new {
Name
= "JB",
Phone ="09XXXXXXXX"
};
//New
function
var myFunc = new Func<dynamic, string>((x)
=> {
return $"{x.Name}:{x.Phone}";
});
//Create
ExpandoObject
dynamic expando = new ExpandoObject();
addProperty(expando, "Profile", myObj);
addMethod(expando, "Show", myFunc);
Console.WriteLine(expando.Show(expando.Profile));
}
private static void
addProperty(ExpandoObject expando, string
propertyName, object propertyValue)
{
//
ExpandoObject supports IDictionary so we can extend it like this
var expandoDict
= expando as IDictionary<string, object>;
if
(expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
private static void addMethod(ExpandoObject expando, string methodName,
Func<object, string>
myMethod)
{
var expandoDict
= expando as IDictionary<string, object>;
expandoDict.Add(methodName, myMethod);
}
Output:
JB:09XXXXXXXX
▌Reference
沒有留言:
張貼留言