struct的使用场景
Demo1、可以当做缓存的key使用
当需要一组参数的值作为缓存key,通常会使用如下方式:
string keyName = arg1+"_"+arg2+"_"+arg3;
此时可以使用struct作为缓存key,只要struct所有属性相同,就会被认为是相同值。不再需要自己拼接缓存key
struct Key
    {
        public string Name { get; set; }
        public Type Type { get; set; }
    }
 private static ConcurrentDictionary<Key, string> cache = new ConcurrentDictionary<Key, string>();
        public static void Main(string[] args)
        {
            var k = new Key { Name="key1",Type=typeof(Program)};
            cache.GetOrAdd(k, key => {
                return JsonConvert.SerializeObject(key);
            });
            k = new Key { Name = "key1", Type = typeof(Program) };
            //会走缓存,因为两次k相同
            cache.GetOrAdd(k, key => {
                return JsonConvert.SerializeObject(key);
            });
      }
Demo2、排重
public struct CountryProvince
{
    public string CountryCode { get; set; }
    public string ProvinceCode { get; set; }
}
List<CountryProvince> list = new List<CountryProvince> {
    new CountryProvince{ CountryCode="A",ProvinceCode="B"},
    new CountryProvince{ CountryCode="A",ProvinceCode="C"},
    new CountryProvince{ CountryCode="A",ProvinceCode="B"}
};
var list2 = list.Distinct();//2

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号