我可以保证什么方法,一个字符串属性是特定长度的? [英] What ways can I ensure that a string property is of a particular length?

查看:95
本文介绍了我可以保证什么方法,一个字符串属性是特定长度的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一些类,将用于提供数据,在我的数据库存储过程。在存储的特效的 VARCHAR 参数的长度规格(如 VARCHAR(6),我想验证所有的字符串属性将它们传递到存储过程之前的长度。

I've created some classes that will be used to provide data to stored procedures in my database. The varchar parameters in the stored procs have length specifications (e.g. varchar(6) and I'd like to validate the length of all string properties before passing them on to the stored procedures.

有一个简单的,声明的方式做到这一点?

Is there a simple, declarative way to do this?

我有两个概念上的想法而已:

I have two conceptual ideas so far:

属性

public class MyDataClass
{
     [MaxStringLength = 50]
     public string CompanyName { get; set; }
}

我不知道是什么程序集/命名空间,我需要用它来实现这种声明性标记。我觉得这个已经存在,但我不知道在哪里,如果是去的最佳途径。

I'm not sure what assemblies/namespaces I would need to use to implement this kind of declarative markup. I think this already exists, but I'm not sure where and if it's the best way to go.

验证在属性

public class MyDataClass
{
     private string _CompanyName;
     public string CompanyName
     {
         get {return _CompanyName;}
         set
         {
              if (value.Length > 50)
                  throw new InvalidOperationException();
              _CompanyName = value;
         }
     }
}

这似乎是一个大量的工作,确实会令我目前简单的类看起来pretty的丑,但我想它会完成这项工作。它也将需要大量复制和粘贴得到这个权利。

This seems like a lot of work and will really make my currently-simple classes look pretty ugly, but I suppose it will get the job done. It will also take a lot of copying and pasting to get this right.

推荐答案

我会后这是一个不同的答案,因为它比code合同特征不同。

I'll post this as a different answer, because it is characteristically different than Code Contracts.

您可以使用具有声明式验证方法之一是使用字典或哈希表的属性存储和共享的实用方法来执行验证。

One approach you can use to have declarative validation is to use a dictionary or hash table as the property store, and share a utility method to perform validation.

例如:

// Example attribute class for MaxStringLength
public class MaxStringLengthAttribute : Attribute
{
    public int MaxLength { get; set; }
    public MaxStringLengthAttribute(int length) { this.MaxLength = length; }
}

// Class using the dictionary store and shared validation routine.
public class MyDataClass
{
    private Hashtable properties = new Hashtable();

    public string CompanyName
    {
        get { return GetValue<string>("CompanyName"); }

        [MaxStringLength(50)]
        set { SetValue<string>("CompanyName", value); }
    }

    public TResult GetValue<TResult>(string key)
    {
        return (TResult)(properties[key] ?? default(TResult));
    }

    public void SetValue<TValue>(string key, TValue value)
    {
        // Example retrieving attribute:
        var attributes = new StackTrace()
                             .GetFrame(1)
                             .GetMethod()
                             .GetCustomAttributes(typeof(MaxStringLengthAttribute), true);
        // With the attribute in hand, perform validation here...

        properties[key] = value;
    }
}

您可以在调用属性使用反射通过努力你的堆栈跟踪的这里证明。反映财产的属性,运行验证和的瞧!的一行代码的getter / setter方法​​具有共同的验证程序。

You can get at the calling property using reflection by working up your stack trace as demonstrated here. Reflect the property attributes, run your validation, and voila! One-liner getter/setters that share a common validation routine.

在顺便说一句,这种模式也方便,因为你可以设计一个类来使用其他类似字典的属性存储,如ViewState中或会话的(ASP.NET中)的,只有更新的GetValue 的SetValue

On an aside, this pattern is also convenient because you can design a class to use alternative dictionary-like property stores, such as ViewState or Session (in ASP.NET), by updating only GetValue and SetValue.

另外一个需要注意的是,你应该使用这个方法,你可以考虑重构验证逻辑到一个验证工具类为所有类型的共享使用。这应该有助于prevent的数据类变得过于笨重的的SetValue 方法。

One additional note is, should you use this approach, you might consider refactoring validation logic into a validation utility class for shared use among all your types. That should help prevent your data class from getting too bulky in the SetValue method.

这篇关于我可以保证什么方法,一个字符串属性是特定长度的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆