动态创建字典

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