2012-01-27 4 views
0
여기

내가 달성하기 위해 노력하고 있습니다 무엇의 샘플입니다기본 클래스 정적 메서드에서 파생 클래스 값에 액세스하려면 어떻게합니까?

기본적으로
public class BaseClass<T> 
{ 
    public static T GetByID(int ID) 
    { 
     // Need database name here that is determined at design time in the derived class. 
     var databaseName = ""; 
     // do some stuff involving database name that gets me object by ID here. 
     return default(T); 
    } 
} 
public class DerivedClass : BaseClass<DerivedClass> 
{ 
    private string DatabaseName { get; set; } 
} 

, 나는 기본 클래스의 정적 GetByID 방법에서 파생 된 "데이터베이스 이름"에 접근 할 방법?

편집 : 게시 한 후에 한 가지 더 시도했습니다. 나는 이전에 속성을 가지고 놀았지만 실패했지만, 나는 두뇌가 흐릿 해 졌다고 생각한다. 그냥 다시 시도하고 테스트를 실행하고, 그것은 작동합니다. 다음은 업데이트 된 샘플입니다. 파생 클래스에

public class BaseClass<T> 
{ 
    public static T GetByID(int ID) 
    { 
     // Need database name here that is determined at design time in the derived class. 
     var databaseName = ((DatabaseAttribute)typeof(T).GetCustomAttributes(typeof(DatabaseAttribute), true).First()).DatabaseName; 
     // do some stuff involving database name that gets me object by ID here. 
     return default(T); 
    } 
} 
[Database("MyDatabase")] 
public class DerivedClass : BaseClass<DerivedClass> 
{ 

} 
public class DatabaseAttribute : Attribute 
{ 
    public DatabaseAttribute(string databaseName) 
    { 
     DatabaseName = databaseName; 
    } 
    public string DatabaseName { get; set; } 
} 
+0

정적 초기화 프로그램에 데이터베이스 이름 설정을 추가하는 것이 좋지 않습니까? –

답변

0

기본 클래스는 단방향 상속입니다 : 기본 클래스는 파생 클래스의 실존에 대한 지식이없는, 그래서 그것을 액세스 할 수 없습니다.

정적 메서드에서 비 정적 속성에 액세스하는 데 어려움을 겪을 것입니다.

0

내가 아는 당신은 이미 자신의 질문에 대답했지만, 일부 개선 ....

절은 상속을 보장하는 곳에, 그것은 정적 방법은 상속 방법을 활용할 수 있음을 의미 추가합니다. 상속 된 클래스의 인스턴스를 만들려면 new() 절을 추가 할 수도 있습니다.

public class BaseClass<T> : where T : BaseClass<T> 
{ 

    static readonly string databaseName; 


    static BaseClass() { 
     // Setup database name once per type of T by putting the initialization in 
     // the static constructor 

     databaseName = typeof(T).GetCustomAttributes(typeof(DatabaseAttribute),true) 
           .OfType<DatabaseAttribute>() 
           .Select(x => x.Name) 
           .FirstOrDefault(); 
    } 

    public static T GetByID(int ID) 
    { 
     // Database name will be in the static field databaseName, which is unique 
     // to each type of T 

     // do some stuff involving database name that gets me object by ID here. 
     return default(T); 
    } 
} 

[Database("MyDatabase")] 
public class DerivedClass : BaseClass<DerivedClass> 
{ 

} 

public class DatabaseAttribute : Attribute 
{ 
    public DatabaseAttribute(string databaseName) 
    { 
     DatabaseName = databaseName; 
    } 
    public string DatabaseName { get; set; } 
} 
관련 문제