C#, 利用dynamic宣告變數
利用dynamic宣告變數
using System;
class Program
{
static void Main()
{
// 宣告 dynamic 物件
dynamic dynamicObject = new { Property1 = "Value1", Property2 = 42, Property3 = true };
// 取得屬性值
string value1 = dynamicObject.Property1;
int value2 = dynamicObject.Property2;
bool value3 = dynamicObject.Property3;
// 顯示取得的值
Console.WriteLine($"Property1: {value1}");
Console.WriteLine($"Property2: {value2}");
Console.WriteLine($"Property3: {value3}");
}
}
利用dynamic宣告空的變數, 動態指定屬性資料
using System;
class Program
{
static void Main()
{
// 宣告 dynamic 變數
dynamic dynamicObject = new System.Dynamic.ExpandoObject();
// 給動態變數不同的屬性名稱和值
dynamicObject.Property1 = "Value1";
dynamicObject.Property2 = 42;
dynamicObject.Property3 = true;
// 讀取動態變數的屬性
string value1 = dynamicObject.Property1;
int value2 = dynamicObject.Property2;
bool value3 = dynamicObject.Property3;
// 顯示讀取的值
Console.WriteLine($"Property1: {value1}");
Console.WriteLine($"Property2: {value2}");
Console.WriteLine($"Property3: {value3}");
}
}
缺點 : 使用dynamic變數時, 打"點"之後不會自動顯示可用屬性, 需手動輸入屬性名稱
dynamic變數跨類別後, 就無法直接取得屬性值
(在偵錯模式雖然看得到值, 但讀取時會顯示無此屬性), 這時可以使用Reflection來取得屬性名稱。
public static object GetDynamicValue(string PropertyName, dynamic dynData )
{
object o = null;
Type type = dynData.GetType();
//取得集合(List)內的型別
PropertyInfo[] classProperties = type.GetProperties();
foreach (PropertyInfo property in classProperties)
{
if (property.Name == PropertyName)
{
o = property.GetValue(dynData);
break;
}
}
return o;
}
public static Main()
{
dynamic obj = new { p1 = "123", p2 = 456};
string p1Value = GetDynamicValue("p1", obj); //p1Value="123"
}
也可以轉個彎, 先把dynamic object轉為JSon格式字串, 使用string方式傳到方法內, 再反轉回dynamic Object, 這時dynamic Object就可以直接使用屬性取得值
反序列化(JSON字串轉C# Class)
using Newtonsoft.Json;
class Program
{
static void Main()
{
string jsonString = @"
[
{""Name"":""John"",""Country"":""USA"",""Age"":25},
{""Name"":""Alice"",""Country"":""Canada"",""Age"":30},
{""Name"":""Bob"",""Country"":""UK"",""Age"":22}
]";
// 反序列化為 List<MyClass>
var myObjects = JsonConvert.DeserializeObject<List<MyClass>>(jsonString);
// 輸出結果
foreach (var obj in myObjects)
{
Console.WriteLine($"姓名: {obj.Name}, 國家: {obj.Country}, 年紀: {obj.Age}");
}
}
}
序列化(C# Class轉JSON字串)
using Newtonsoft.Json;
class Program
{
static void Main()
{
List<MyClass> myObjects = new List<MyClass>
{
new MyClass { Name = "John", Country = "USA", Age = 25 },
new MyClass { Name = "Alice", Country = "Canada", Age = 30 },
new MyClass { Name = "Bob", Country = "UK", Age = 22 }
};
// 序列化為 JSON 字符串
string jsonString = JsonConvert.SerializeObject(myObjects, Formatting.Indented);
// 輸出結果
Console.WriteLine(jsonString);
}
}
留言
張貼留言