c# - 静态覆盖/抽象方法 - 有什么好的解决方法吗?

标签 c#

我有一个抽象的基本配置类和两个实现:

public abstract class BaseConfiguration
{
}

public class LoginConfiguration : BaseConfiguration
{
    public LoginConfiguration() 
    {
    }

    public string Name { get; set; }
    public string Password { get; set; }
}

public class TestConfiguration : BaseConfiguration
{
    public TestConfiguration()
    {
    }
}

我遇到的问题: 每个特定的类类型都有一个它指向的显式文件名。这意味着 LoginConfiguration 有一个名为“login.xml”的文件名,而 TestConfiguration 指向“test.xml”。

稍后我想用于反序列化的文件名:

static void Main(string[] args)
{
    LoginConfiguration login = ReadFromFile<LoginConfiguration>();
    Console.ReadLine();
}

private static TConfig ReadFromFile<TConfig>() where TConfig : BaseConfiguration
{
    //Something like this needs to be done here:
    string filename = TConfig.GetFilename();

    //Deserialize file and return object
    return Deserialize<TConfig>(filename);
}

但我知道你既不能有静态覆盖也不能有静态抽象方法。

我目前正在做的是使用基类来实例化一个新对象并从该实例中读取文件名,但这非常 hacky。

public abstract class BaseConfiguration
{
    protected BaseConfiguration(string fileName)
    {
        Filename = fileName;
    }

    public string Filename { get; private set; }

    public static string GetFilename<TConfig>() where TConfig : BaseConfiguration, new()
    {
        return new TConfig().Filename;
    }
}

//The calling method:
private static TConfig ReadFromFile<TConfig>() where TConfig : BaseConfiguration, new()
{
    string filename = BaseConfiguration.GetFilename<TConfig>();
    //Deserialize file and return object
    return Deserialize<TConfig>(filename);
}

我现在的问题是: 你有什么想法,我怎样才能更好地设计它?你有更好的方法吗? C# 中的静态抽象方法在此类问题上是否有意义?

提前致谢!

最佳答案

如果你不介意反射(reflection)一下,你可以添加一个属性来提供文件名:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ConfigFileAttribute : Attribute
{
    ...
}

[ConfigFile("login.xml")]
public class LoginConfiguration 
{
    ...
}

因为您已经有了类型 (TConfig),您可以使用以下方法访问该属性:

var configAttributes = typeof(TConfig).GetCustomAttributes(typeof(ConfigFileAttribute), false);

当然这确实意味着忘记属性会导致读取失败。

这不是“最佳”解决方案,但我个人更喜欢单独管理文件名,类本身对此不感兴趣。

关于c# - 静态覆盖/抽象方法 - 有什么好的解决方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35450276/

相关文章:

c# - json.net 与 DataContractJsonSerializer

c# - 使用 geoshape 属性映射创建索引

c# - 如何将数据导出到 Excel 文件

c# "is"与变量中存储的类型进行比较--

c# - ASP.NET MVC/C# : Can I avoid repeating myself in a one-line C# conditional statement?

C# 生成类到命名空间

c# - 将 ASP.net 身份用户与其他表一起使用

c# - Cross Thread错误处理形式与Timer

c# - 达到内存限制会降低 .Net 应用程序的速度

c# - 如何在c#中使用SQL Server存储过程数字参数