【问题标题】:How to find the value of an attribute如何找到属性的值
【发布时间】:2011-06-20 19:01:21
【问题描述】:

如何找到属性的值?我需要检查该值并将文本框 maxlength 设置为该值。这是我要检索的值的示例。

public class DogClass
    {
        [StringLength(5)]
        public string LegalName
        {
        }

【问题讨论】:

  • 你的意思是像 return _LegalName ?
  • 我需要以某种方式返回 5。所以我可以将文本框 maxlength 设置为 5

标签: sql winforms entity-framework-mapping


【解决方案1】:

您可以使用反射来获取此信息。下面是一个可以帮助您入门的 sn-p。

protected void GetStringLength(object objDog) {
    // loop through each property in object
    foreach (PropertyInfo pi in objDog.GetType().GetProperties())
    {
        // for each object property, get the SringLength tag (if there is one)
        foreach (Attribute attribute in Attribute.GetCustomAttributes(pi, typeof(StringLengthAttribute), true))
           {
                // we'll assume there is only one 
                var stringLenVal = (attribute as StringLengthAttribute).MaximumLength;
                break;
           }
    }
}

【讨论】:

    猜你喜欢
    • 2017-05-17
    • 1970-01-01
    • 2017-08-20
    • 2013-02-28
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    相关资源
    最近更新 更多