编程语言
首页 > 编程语言> > DynamicJS 让c#像js一样灵活

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));
    }
}

标签:name,c#,object,js,dic,ignoreCase,value,DynamicJS,public
来源: https://www.cnblogs.com/boring246/p/16343173.html