簡體   English   中英

StringLengh數據注釋使用靜態屬性

[英]StringLengh Data Annotation using a static property

我想在實體上使用StringLength屬性,而不是使用文字或常量來使用靜態屬性。

例如

[StringLength(MyClass.MyStaticProperty)]
public string Code { get; set; }

但是,這會導致以下錯誤......

屬性參數必須是屬性參數類型的常量表達式,typeof表達式或數組創建表達式

...除了使用字符串文字或常量之外,有沒有人有工作或替代?

萬一你想知道為什么一個靜態屬性? static屬性將從注入的單例中返回一個值。 該值將在應用程序啟動時注入。

謝謝......聖誕快樂......

創建自己的屬性可能是最好的解決方案。 然后,您還可以控制以后可能要實現的任何其他邏輯。

public class CustomStringLength: ValidationAttribute
{
    public CustomStringLength()
    {
    }

    public override bool IsValid(object value)
    {
        return (string)value.Length == MyClass.MyStaticProperty;
    }
}

考慮到MyClass.MyStaticProperty是一個int

用法:

[CustomStringLength]
public string Code { get; set; }

StringLength屬性參數應該在編譯時知道。

您可以指定確切的值或引用常量值:

public static class MyClass
{
    public const int MyStaticProperty = 5;
}

[StringLength(MyClass.MyStaticProperty)]
public string Code { get; set; }

請注意,沒有static關鍵字,因為const意味着static

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM