내가 달성하기 위해 노력하고 있습니다 무엇의 샘플입니다기본 클래스 정적 메서드에서 파생 클래스 값에 액세스하려면 어떻게합니까?
기본적으로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; }
}
정적 초기화 프로그램에 데이터베이스 이름 설정을 추가하는 것이 좋지 않습니까? –