DynamicJS 让c#像js一样灵活
2022/6/5 1:20:07
本文主要是介绍DynamicJS 让c#像js一样灵活,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
0 知识点
首先,第一点,通过 public object this[string name]
处理字典值,其次利用 DynamicObject
转换动态类。
1 Dynamic
参考:动态类型
2 让c#像js一样灵活
/// <summary> /// 动态js类 /// </summary> [JsonConverter(typeof(DynamicJsJsonConverter))] public class DynamicJS : DynamicObject { private readonly Dictionary<string, object> dic = new Dictionary<string, object>(); private readonly bool _ignoreCase; /// <summary> /// 动态js类 /// </summary> /// <param name="ignoreCase">忽略大小写</param> public DynamicJS(bool ignoreCase = false) { _ignoreCase = ignoreCase; } public int Count { get => dic.Count; } public object this[string name] { get { name = _ignoreCase ? name.ToLower() : name; if (dic.TryGetValue(name, out object value)) { return value; } return null; } set { name = _ignoreCase ? name.ToLower() : name; dic[name] = value; } } public override bool TryGetMember(GetMemberBinder binder, out object result) { string name = _ignoreCase ? binder.Name.ToLower() : binder.Name; return dic.TryGetValue(name, out result); } public override bool TrySetMember(SetMemberBinder binder, object value) { string name = _ignoreCase ? binder.Name.ToLower() : binder.Name; dic[name] = value; return true; } /// <summary> /// 重写json序列化 /// </summary> /// <returns></returns> public override string ToString() { return JsonConvert.SerializeObject(dic); } public Dictionary<string, object> Value { get => dic; } } public class DynamicJsJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = ""; if (value is System.Dynamic.DynamicObject) { result = value.ToString(); } writer.WriteRaw(result); } }
3 来吧 内卷!
class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); dynamic dynamicJS = new DynamicJS(); dynamicJS["AA"] = "aaaa"; dynamicJS.a = 11; dynamicJS.List = new List<int> { 123, 555, 666 }; Console.WriteLine(JsonConvert.SerializeObject(dynamicJS)); } }
这篇关于DynamicJS 让c#像js一样灵活的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用