具有非静态列表的静态属性< T> [英] Static property with non-static list<T>

查看:67
本文介绍了具有非静态列表的静态属性< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态属性返回带有生成的模拟数据的List。



在这个例子中,我从字符串创建IPAddress以模拟来自移动设备的IP。

内存泄漏的风险是什么?

A Static property returns a List with generated Simulation Data.

In this example I create IPAddress from strings to simulate IPs from a mobile device.
What are the risc of memory leaks?

static readonly string[] IPv6Simu = { "fe80::3a6d:eeeb:8bff:4ef2", "fc01:abab:cdcd:efe0:49d2:473:579c:cfaa" };
   static readonly string[] IPv4Simu = { "172.22.1.100", "172.22.1.100" };
   static readonly string[] InterfaceName = { "mnet1", "mnet0" };

  public static List<IpData> StaticSimulateIPFactory
   { get
       {
           List<IpData> simu = new List<IpData>();
           try
           {
               IPAddress ip;
               foreach (var IPv6 in IPv6Simu)
               {
                   if (IPAddress.TryParse(IPv6, out ip))
                   {
                       simu.Add(new IpData() { InterfaceName = InterfaceName.FirstOrDefault(), IPAddress = ip });
                   }
               }
               foreach (var IPv4 in IPv4Simu)
               {
                   if (IPAddress.TryParse(IPv4, out ip))
                   {
                       simu.Add(new IpData() { InterfaceName = InterfaceName.FirstOrDefault(), IPAddress = ip });
                   }
               }
               return simu;
           }
           catch (Exception)
           {
               simu.Add(new IpData() { InterfaceName = "INV", IPAddress = new IPAddress(new byte[]{127,0,0,1} )});
               return simu;
           }
       }
   }





我尝试了什么:



另一种方法是使所有非静态。不是问题,但我想在静态方法中使用这个模拟值。



What I have tried:

The other approach is to make all non static. not a Problem, but I want to use this Simulation Value in a static method.

推荐答案

没有内存泄漏 - 你觉得这样吗? - 但不需要在每次访问属性时反复重新创建相同的列表。只需创建一个静态List变量并初始化一次(如果为null),然后返回列表。
No memory leak - wyh do you think that? - but no need to recreate the same list again and again on every property access. Just make a static List variable and initialize once (if null), then return the list.


这篇关于具有非静态列表的静态属性&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆