c#操作缓存例如redis比较推荐ServiceStack
在redis中运用key-value存储数据,但是遇到结构体该如何处理,是类可通过get<type>(key)获得,那struct呢,
定义结构:
1 public struct Person{ 2 public int id; 3 public double lon; 4 public double lat; 5 }
redis中设置值:
1 Random rand=new Random(); 2 Person info=new Person(); 3 for(int i=0;i<3;i++) 4 { 5 info.id=id+i; 6 info.lon=rand.NextDouble(); 7 info.lat=rand.NextDouble(); 8 client.Set<string>(info.id.ToString(),info.ToString()); 9 }
运行查看出现异常:
为什么在使用结构体时候会出现异常,而class确可以。
涉及到.net中对结构体与class直接区别,结构体是一种值类型非引用类型。
C#的所有值类型均隐式派生自System.ValueType:
结构体:struct(直接派生于System.ValueType)
难道ServiceStack只能存储不能获取struct么?
非也,进入ServiceStack text项目:https://github.com/ServiceStack/ServiceStack.Text
会发现如下一段内容,在项目中如何处理值类型与结构体:
C# Structs and Value Types Because a C# struct is a value type whose public properties are normally just convenience properties around a single scalar value,
they are ignored instead the TStruct.ToString() method is used to serialize and either the static TStruct.ParseJson()/static TStruct.ParseJsv()
methods or new TStruct(string) constructor will be used to deserialize the value type if it exists.
存在TStruct.ToString()及static TStruct.ParseJson()/static TStruct.ParseJsv() 可以实现反序列化。
可以通过重写ToString()方法及新增static ParseJson()等实现。
修改结构体如下:
1 public struct Person{ 2 public int id; 3 public double lon; 4 public double lat; 5 6 public override string ToString() 7 { 8 return string.Format("[{0}, {1}, {2}]", id, lon, lat); 9 } 10 11 public static Person Parse(string json){ 12 var arr=json.Trim('[',']').Split(','); 13 return new Person{ id=int.Parse(arr[0]),lon=double.Parse(arr[1]),lat=double.Parse(arr[2])}; 14 } 15 }
之前异常部分代码:
结构体是否可以转化呢?