【问题标题】:Update a value outside a class and keep it alive in C#?更新类外的值并在 C# 中保持活动状态?
【发布时间】:2020-09-18 17:34:08
【问题描述】:

好吧,我在一个基本的范围问题上苦苦挣扎(在我看来),我想从外部更新我的变量解决方案并保持它的活力(在 CProperties 类中)以将它传递到我的字典中,所以我保持相同的键不同的价值。

ps:我必须保持 Dictionary() 格式(对于 Api)(是的,我更喜欢 string, string[])

pps:我来自 C++

这样做的正确方法是什么?

public static class CProperties
{
   public static string solution { get; set; }
            
   static public Dictionary<string, string> product = new Dictionary<string, string>()
   {
       { "product_name", solution}
   };
}
static void mycrazyFunc()
{   
            // I skip the Database connection and everything
            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());
        
             if (dt.Rows.Count > 0)
             {
                 foreach (DataRow rows in dt.Rows)
                 {
                     dynamic JsonObj = new ExpandoObject();
            
                     if (!string.IsNullOrEmpty(rows["Product"].ToString()))
                     {
                        CProperties.solution = rows["Product"].ToString(); // Got the value !
                        JsonObj.custom_fields = CProperties.product;       // Lost the value ! 
                                                                           // {"product_name", "null"}
                     }
                 }
             }
}

【问题讨论】:

  • 您没有丢失价值,它从未被放入product。当product被初始化时,solution就是null;这就是字典中的内容,而不是对 solution 属性的引用。更改 solution 不会更改 product["product_name"] (反正不是你在这里的方式)。
  • 在你的情况下解释外部,外部类,外部过程,外部机器,你到底需要什么提供更多细节

标签: c# class variables


【解决方案1】:

让 setter 和 getter 读/写字典本身:

public static class CProperties
{
   public static string solution 
   { 
     get{ return product["product_name"]; }
     set{ product["product_name"] = value; }
   }
            
   static public Dictionary<string, string> product = new Dictionary<string, string>()
   {
       { "product_name", null}
   };
}

或根据需要构建字典

public static class CProperties
{
   public static string solution { get; set; }
            
   static public Dictionary<string, string> product => new Dictionary<string, string>()
   {
       { "product_name", solution}
   };
}

两者都适合你。


但除此之外,你的问题是

这样做的正确方法是什么?

可以说正确的方法是完全摆脱CProperties,因为它没有任何实际用途,只是直接设置字典:

JsonObj.custom_fields = new Dictionary<string,string>{ 
       ["product_name"] = rows["Product"].ToString() 
};

【讨论】:

  • 这绝对是我想要的。因为它是从无限循环中调用的,所以第一个选项对我来说在内存管理方面看起来更好,但从 C++ 的角度来看可能不太安全,哈哈。无论如何谢谢 =)
  • @Designart 我不知道您的初始代码是否有些做作,但在我看来,CProperties 根本没有用,您应该将JsonObj.custom_fields 设置为新字典。 JsonObj.custom_fields = new Dictionary&lt;string,string&gt;{ ["product_name"] = rows["Product"].ToString() };
  • 其实是的,你是对的。最初的想法是不复制代码,因为我必须从不同的方法调用它(这就是为什么从不同的地方设置某些东西可能并不安全)以将字典作为输入发送到 Api。但最终我可能只有一种方法
猜你喜欢
  • 1970-01-01
  • 2013-09-07
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 2011-09-16
相关资源
最近更新 更多