将常量值每个实例存储? [英] Would const values be stored per instance?

查看:118
本文介绍了将常量值每个实例存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关这样的类型:

public class BlurEffect
{
    public const string Name = "Blur";

    public int Amount {get;set;}
}

我有几个成员如 .Name点,这将是在所有成员一样,我应该让静态的呢?

I have a few members like .Name, that will be the same across all members, should I make it static instead?

我只是不希望它每个实例存储,或使用更多的资源比必要的,他们也应该是只读的。

I just don't want it to be stored per instance, or use more resources than necessary, and they should also be read-only.

最后,我想实例访问它,所以我可以说:

Lastly I want instance access for it so I can say:

blurEffect.Name

blurEffect.Name

我应该返回一个私有的静态变量名称属性?这是最好的方法是什么?

Should I make a Name property that returns a private static variable? Is this the best way?

推荐答案

常量,在C#中,实际上是解决了在编译时。他们将与随处可见它的编译器使用的值替换,因此,变量(名称)将实际上不存在的编译后的IL。

Constants, in C#, are actually resolved at compile time. They will be replaced with the value everywhere it's used by the compiler, so the "variable" (Name) won't actually exist in the resulting compiled IL.

字符串常量,此外,拿实习,所以有模糊的只有一个副本将在您的可执行文件被加载,无论其使用多少次。

String constants, in addition, get interned, so there is only one copy of "Blur" that will be loaded in your executable, no matter how many times its used.

就个人而言,我会用一个私人const和公共变量:

Personally, I would use a private const and a public variable:

public class BlurEffect
{
    private const string name = "Blur";
    public string Name { get { return name; } }

    public int Amount {get;set;}
}

这让你的基于实例的使用,并且仍然有一个恒定的,你可以操纵。

This gets you your instance-based usage, and still has a single constant you can manipulate.

这篇关于将常量值每个实例存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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