STNodeEditor icon indicating copy to clipboard operation
STNodeEditor copied to clipboard

STNode 定义只读属性保存后,再读取时会报异常

Open AzThinker opened this issue 3 years ago • 3 comments

假如定义如下属性 [STNodeProperty("Name", "唯一标识")] public string Name { get { return this.Guid.ToString(); } } 则在保存后,再打开会出现异常。 我定义了如下特性 public class STNoSaveAttribute: Attribute { } 并修改 STNode的OnSaveNode事件中 foreach (var p in t.GetProperties()) { var attrs = p.GetCustomAttributes(true); // 增加检测 if (attrs.Where(s => s is STNoSaveAttribute).Count() > 0) continue; …… }

这样就没有错误了 只是一种方案,也许有更好的。

AzThinker avatar Sep 20 '22 08:09 AzThinker

是的这个问题我也发现了。 我发现关于节点的存储方面纯在这很多的问题。这两天也在整理一些思路。 关于只读属性其实还可以这样

var ps = type.GetProperties();
foreach (var p in ps) {
    var mi = p.GetSetMethod();  // 获取属性 Set 访问器,如果只读属性 mi = null
    if (mi != null) {
        try {
            //mi.Invoke(...)
            p.SetValue(obj, value);
        } catch (Exception ex) {
            // ...
        }
    }
}

在保存的时候也可以通过检测访问器来判断只读属性 如果是只读直接绕过保存。 在.NET属性只是一个便捷的语法 可以直接[XXX.XXX]的方式去调用。但本质还是函数执行的。

DebugST avatar Sep 20 '22 08:09 DebugST

这样也可以的。 如果想序列化到数据库,或者成json格式的数据时,并不是所有的属性值都需要序列化。所以,增加几个标记特性,也是一种不错的选择。

AzThinker avatar Sep 20 '22 09:09 AzThinker

是的,新的特性会增加。

enum SaveModel{
All,
OnlyMarked,
ExcludeMarked
}
[STNode(...,SaveModel.MarkedOnly)]
public class XXXNode : STNode{
    public int Test_1{get;set}
    [STNodeProperty("key","description"),STNodePropertyMark]
    public int Test_2{get;set}
}

名称暂定。

DebugST avatar Sep 20 '22 09:09 DebugST