C#4.0可选参数问题

时间:2011-01-03 14:09:21

标签: c#-4.0

我有类似的实现:

 public interface IGenericRepository
 {
    //...
    void Update<T>(T entity, string keyPropertyName = "Id") where T : class;
    void Delete<T>(T entity, string keyPropertyName = "Id") where T : class;
    //...
}

public abstract class GenericRepositoryBase : IGenericRepository
{
    //...
    void Update<T>(T entity, string keyPropertyName = "Id") where T : class;
    void Delete<T>(T entity, string keyPropertyName = "Id") where T : class;
    //..
}

public class GenericRepository : GenericRepositoryBase
{
    //..
    public override void Update<T>(T entity, string keyPropertyName = "Id")
    {
       //..
    }

    public override void Delete<T>(T entity, string keyPropertyName = "Id")
    {
        //..
    }
    //..
}

每当我指定(硬编码)keyPropertyName =“Id”时,它看起来都不好。

可能有人知道如何在一个地方宣布价值const string defaultKeyPropertyName = "Id"然后到处都是这样使用。

//...
void Update<T>(T entity, string keyPropertyName = defaultKeyPropertyName) where T : class;
void Delete<T>(T entity, string keyPropertyName = defaultKeyPropertyName) where T : class;
//..

或者可以以其他方式完成?

任何想法?

3 个答案:

答案 0 :(得分:3)

如果需要,您可以使用const,并创建一个包含它的类。 C#没有全局变量的概念,因此它尽可能接近:

public static class Defaults
{
    public const string KeyName = "Id";        
}

public abstract class GenericRepositoryBase
{
    //...
    protected abstract void Update<T>(T entity, string keyPropertyName = Defaults.KeyName) where T : class;
    protected abstract void Delete<T>(T entity, string keyPropertyName = Defaults.KeyName) where T : class;
    //..
}

答案 1 :(得分:1)

AFAIK可选参数值必须是常量,因此您无法在任何地方声明它们。

答案 2 :(得分:0)

也许你没有在接口中定义keyPropertyName的默认值,但是在抽象类中,你可以在抽象类中引入常量。

相关问题