验证动态对象中的属性

Validating properties in dynamic objects

我正在使用 Scriban 为邮件服务呈现 html 模板。 Scriban 允许我渲染 html,使用对象和 html 模板,如下所示:

<ul id='model'>\n<h2>Name 2: {{ model.Username }}</h2>\n<h1>Message 2: {{ model.Password }}</h1>\n</ul>

我需要验证动态对象中是否存在某些属性。在上面的例子中,匹配的动态对象需要包含一个“用户名”属性和一个“密码”属性.


我已经创建了一个可行的解决方案,但它非常笨拙,让我羞于称自己为开发人员,并且绝不会成为我最终解决方案的一部分:

    private readonly string template = "<ul id='model'>\n<h2>Name 2: {{ model.Username }}</h2>\n<h1>Message 2: {{ model.Password }}</h1>\n</ul>";
    private readonly dynamic model = new {Username = "user1", Password = "pass"};
    public void Validate()
    {
        //Convert dynamic object to dictionary
        var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(model));
        //Regex pattern for finding properties in html-string
        Regex pattern = new Regex("(?<={{ )(.*?)(?= }})");
        //Properties in html-string
        MatchCollection matches = pattern.Matches(template);

        //Check if dynamic object contains a property for each match
        foreach (Match match in matches)
        {
            var matchString = match.ToString();
            //Remove "model." from match. This should be done by regex instead.
            var property = matchString.Substring(matchString.IndexOf('.') +1);
            //Throws an exception, if the dynamic object doesnt contain the property.
            var result = data[property];
        }  
    }

如何验证某个 属性 是否存在于动态对象中?

您应该尝试使用 Dynamic 对象 class,您的模型可以继承自 class。这将允许您控制当您尝试 set/access 动态对象成员时发生的情况。

The DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication.

详情见:https://docs.microsoft.com/en-us/dotnet/api/system.dynamic.dynamicobject?view=netframework-4.7.2