C#,silverlight,检查 ref 传递的字段是否应用了属性

发布于 2024-12-18 09:28:31 字数 260 浏览 2 评论 0原文

在基类中,我对派生类有以下方法:

protected virtual void SetValue<T>(ref T field, string propertyName, T value)
{
   //assign value to the field and do some other staff 
   ...
}

有什么方法可以检查 fieldVar 是否应用了属性(例如 DataMemberAttribute)?

In a base class I have the following method for derived classes:

protected virtual void SetValue<T>(ref T field, string propertyName, T value)
{
   //assign value to the field and do some other staff 
   ...
}

Is there any way to check if fieldVar has an attribute applied (for example DataMemberAttribute)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

私藏温柔 2024-12-25 09:28:31

不,没有办法做到这一点,除了看起来你也被告知了属性名称。

如果你能找到字段的 FieldInfo,那么你就可以找到任何属性,但不能单独通过 ref 参数。

No, there is no way to do that, except that it looks like you're also told the property name.

If you can find the FieldInfo of the field, then you can find any attributes, but not through the ref-parameter alone.

铁轨上的流浪者 2024-12-25 09:28:31

从字里行间看,您有一组支持公共属性值的私有字段。在部分或全部这些属性上,您附加了一些您想要发现的数据属性。

 PropertyInfo pi = this.GetType().GetProperty(propertyName);
 object[] dataMemberAttributes = pi.GetCustomAttributes(typeof(DataMemberAttribute, true);
 if (dataMemberAttributes.Length > 0)
 {
     DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)dataMemberAttributes[0];
     // Do stuff with the attribute.
 }

Reading between the lines you have a set of private fields which back the values of public properties. On some or all of these properties you some data attributes attached that you want to discover.

 PropertyInfo pi = this.GetType().GetProperty(propertyName);
 object[] dataMemberAttributes = pi.GetCustomAttributes(typeof(DataMemberAttribute, true);
 if (dataMemberAttributes.Length > 0)
 {
     DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)dataMemberAttributes[0];
     // Do stuff with the attribute.
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文