开发者

C# - Global internal const?

开发者 https://www.devze.com 2023-03-16 12:19 出处:网络
I\'m trying to do the following: [FooAttribute(Value = String.Format(\"{0} - {1}\", myReources.BaseString, \"Bar\"))]

I'm trying to do the following:

[FooAttribute(Value = String.Format("{0} - {1}", myReources.BaseString, "Bar"))]
public int FooBar { get; set; }

The compiler complains though... so what is the correct way to do it where I have my BaseString in one location? My code is littered with attributes on the properties inside my library, so "glob开发者_运维百科al" internal const sound like the solution since I can't use resources.


You can't have expressions like string.Format in an attribute...but the following should work:

public class MyResources
{
    public const string BaseString = "there";
}

[FooAttribute(Value = MyReources.BaseString + " - Bar"))]
public int FooBar { get; set; }


If you remove the String.Format and use basic string concatenation, the compiler will not complain. Since String.Format is resolved at runtime and not compile time, you can't use it in attributes. The compiler will recognize that both the myResources.BaseString and "Bar" are constant values so it's legal to do this.

[FooAttribute(Value = myReources.BaseString + "Bar")]

0

精彩评论

暂无评论...
验证码 换一张
取 消