简体   繁体   English

动态创建字典

[英]Dynamically creating a dictionary

I have a said class given below:我在下面给出了 class:

 public class ABC : XYZ
{
    public string Username { get; set; }
    public string Password { get; set; }
}

I am passing this class into another class as:我将这个 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);
    }
}

Is there a way to dynamically do this?有没有办法动态地做到这一点? What I mean is I don't want to keep stating the dic.Add("password", _ABC.Password);我的意思是我不想继续说明dic.Add("password", _ABC.Password); for each key-value pair I want to enter in the dictionary.对于我想在字典中输入的每个键值对。 There are multiple records and I'd like to loop through them, if there is a way.有多个记录,如果有办法的话,我想遍历它们。 I am also quite new to C# so please let me know if you need any other information.我对 C# 也很陌生,所以如果您需要任何其他信息,请告诉我。

I had to make some corrections to run, but you can do it using the code below.我必须进行一些更正才能运行,但您可以使用下面的代码来完成。 I'm using .NET 6 but it will run for previous versions.我正在使用 .NET 6 但它会运行以前的版本。

foreach(var prop in _ABC.GetType().GetProperties())
        {
            _dic.Add(prop.Name, _ABC.GetType().GetProperty(prop.Name).GetValue(_ABC, null).ToString());
        } 

Example:例子:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM