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一样灵活的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程