[英]Dynamically creating a dictionary
我在下面給出了 class:
public class ABC : XYZ
{
public string Username { get; set; }
public string Password { get; set; }
}
我將這個 class 傳遞給另一個 class 作為:
public class otherClass : someClass, someInterface
{
private readonly ABC _ABC;
public PythonRunner(ILogger<com> logger, ABC ABC)
: base(logger, acpApiService, apxApiService, logAttributes, mapper)
{
ABC = ABC;
}
Public Void SomeFunc()
{ Console.WriteLine(_ABC.username)
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("username", _ABC.Username);
dic.Add("password", _ABC.Password);
}
}
有沒有辦法動態地做到這一點? 我的意思是我不想繼續說明dic.Add("password", _ABC.Password);
對於我想在字典中輸入的每個鍵值對。 有多個記錄,如果有辦法的話,我想遍歷它們。 我對 C# 也很陌生,所以如果您需要任何其他信息,請告訴我。
我必須進行一些更正才能運行,但您可以使用下面的代碼來完成。 我正在使用 .NET 6 但它會運行以前的版本。
foreach(var prop in _ABC.GetType().GetProperties())
{
_dic.Add(prop.Name, _ABC.GetType().GetProperty(prop.Name).GetValue(_ABC, null).ToString());
}
例子:
var user = new UserModel()
{
Username = "Someone",
Password = "SafePassword"
};
var other = new OtherClass(user);
other.PrintDictonary();
public class UserModel
{
public string Username { get; set; }
public string Password { get; set; }
}
public class OtherClass
{
private readonly UserModel _ABC;
private Dictionary<string, string> _dic = new Dictionary<string, string>();
public OtherClass(UserModel ABC)
{
_ABC = ABC;
SomeFunc();
}
public void SomeFunc()
{
foreach(var prop in _ABC.GetType().GetProperties())
{
_dic.Add(prop.Name, _ABC.GetType().GetProperty(prop.Name).GetValue(_ABC, null).ToString());
}
}
public void PrintDictonary()
{
foreach(KeyValuePair<string, string> entry in _dic)
{
Console.WriteLine($"Key: { entry.Key } Value { entry.Value }");
}
}
}
//It will print in console:
//Key: Username Value Someone
//Key: Password Value SafePassword
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.