2011-01-03 6 views
2

내가 구현처럼이 질문 :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 = (하드 코딩) "이드"그렇지 좋은 찾고 있습니다.

어떤 사람이 단지 한 곳에서 값 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

원하는 경우 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

AFAIK 선택적 매개 변수 값은 상수 여야하므로 아무 곳에 나 선언 할 수 없습니다.

+1

진술의 전반부는 정확하지만 상수는 (거의) 어디에서나 선언 할 수 있습니다. – grenade

0

은 어쩌면 당신은 인터페이스에 keyPropertyName에 대한 기본 값을 정의하지 않지만, 추상 클래스에서, 당신은 소개 할 수 abstract 클래스의 정수

+0

나는 그랬지만, 그런 경우 Optional Parameter string keyPropertyName은 선택적인 것이 아니라,이 선택적인 것도 지키려고했다. – Kuncevic