从派生类重写公共属性

pet*_*rbf 7 c# inheritance overriding

在一个旧项目中,我们使用的第三方程序集具有一个具有一些硬编码信息的属性的类:

public string ConnectionString
{
    get
    {
        string[] fullDbName = new string[5];
        fullDbName[0] = "Data Source=";
        fullDbName[1] = this.dbServer;
        fullDbName[2] = ";Initial Catalog=";
        fullDbName[3] = this.FullDbName;
        fullDbName[4] = ";Integrated Security=SSPI;Pooling=false";
        return string.Concat(fullDbName);
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要能够自己构建连接字符串.所以我试图创建一个隐藏原始属性的派生类,但它似乎不起作用:

public class SqlServerRestorerExstension : SQLServerRestorer
{
    public SqlServerRestorerExstension(string dbServer, string dbName, string dbFilePath, string dbDataFileName, string dbLogFileName, bool detachOnFixtureTearDown, string connectionstring) : base(dbServer, dbName, dbFilePath, dbDataFileName, dbLogFileName, detachOnFixtureTearDown)
    {
        ConnectionString = connectionstring;
    }

    public string ConnectionString { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

当我无法访问第三方代码时,是否可以以任何方式实现此目的?

afr*_*hke 9

正如其他人指出的那样,您可以使用该new关键字来隐藏基本成员属性.但请注意,这并没有神奇地将ConnectionString属性转换为多态函数,即如果你有这样的东西:

public class A 
{
    public string CString { get { return "a"; } }
}

public class B : A
{
    public new string CString { get { return "b"; }}
}
Run Code Online (Sandbox Code Playgroud)

你这样做:

A a = new B();

Console.WriteLine(a.CString);
Run Code Online (Sandbox Code Playgroud)

然后你仍会看到打印到控制台的"a".实际上,new关键字只是阻止编译器发出有关隐藏基类成员的警告.它不会在运行时更改代码的行为.

您可以尝试使用Decorator模式并将其包装SQLServerRestorer,但如果这也不起作用,那么我很害怕.