如何在C#中覆盖定义的值?

时间:2014-01-24 13:08:01

标签: c# visual-studio windows-phone-8 windows-8 c-preprocessor

我曾参与iOS项目,现在开始使用Windows Phone,

iOS中的

我已将所有常用类复制到一个文件夹中(比如说是父文件)并将该文件夹链接到不同的项目中,让我们说是子项目。

在常见的类中我有一个名为Constants.m的类,因为我使用一些值大约98个语句来违反所有#define语句,我在所有类中使用它。

在子项目中,我使用的是.pch文件,因为我只定义了项目特定值#define语句,假设有10个值。

现在,当我运行子项目时,无论我在.pch文件中定义了什么值,它都将使用Constants.m中的默认值覆盖这些值,因此我将获得子项目特定值,以及我没有定义的任何值在子项目中,代码将从Constants.h中选择默认值。

我试图在Windows手机应用程序开发中使用类似的东西,我能够链接这些类,但我无法从其他文件中获取#define

How to use #define from another file?

有没有办法可以覆盖定义的值?就像iOS一样。

1 个答案:

答案 0 :(得分:0)

在C#中,您不能使用#define来设置全局常量的值。

在我的头脑中,有两种方法可以在父项目中使用全局常量并在子项目中覆盖它们:

1)使用config(我的个人喜好)

2)使用虚拟属性(如评论中所述)

配置,最简单的形式看起来像

<configuration>
 <appSettings>
  <add key="Setting1" value="Value1" />
  <add key="Setting2" value="Value2" />
 </appSettings>
</configuration>

并且像这样使用

string setting1 = ConfigurationSettings.AppSettings["Setting1"];

虽然我强烈建议您使用custom configuration sections

最简单的

虚拟属性

// in parent project
class ParentValues
{
    public virtual int Key1
    {
        get { return 5; }
    }

    public virtual int Key2
    {
        get { return 10; }
    }
}

// in child project
class ChildValues : ParentValues
{
    public override int Key2
    {
        get
        {
            return 12;
        }
    }
}

并使用

// in child project
class ValueUser
{
    public int GetValue()
    {
        ChildValues cv = new ChildValues();
        return cv.Key2;
    }
}