3
下面鏈接的懶方法獲取繼承的類名的C#小提琴 https://dotnetfiddle.net/4QTGx3在基類
我試圖在基類的靜態方法來檢索繼承的類名。沒有我找到的幫助。
public class Worker
{
public string Id1 {get; set;}
public string Id2 {get; set;}
public string Id3 {get; set;}
}
public interface IModel
{
}
public class Model1: IModel
{
}
public class Model2: IModel
{
}
public class ModelActor <TModel> where TModel: IModel
{
private Lazy<Worker> _worker = new Lazy<Worker>(
() => new Worker()
{
Id1 = new StackFrame().GetMethod().DeclaringType.Name,
Id2 = MethodBase.GetCurrentMethod().DeclaringType.Name,
Id3 = typeof(ModelActor <TModel>).Name
}
);
public Worker Worker
{
get
{
return _worker.Value;
}
}
}
public class ModelActor1: ModelActor<Model1>
{
}
public class ModelActor2: ModelActor<Model2>
{
}
public static void Main()
{
Console.WriteLine("Id1: {0} {1}", new ModelActor1().Worker.Id1, new ModelActor2().Worker.Id1);
Console.WriteLine("Id2: {0} {1}", new ModelActor1().Worker.Id2, new ModelActor2().Worker.Id2);
Console.WriteLine("Id3: {0} {1}", new ModelActor1().Worker.Id3, new ModelActor2().Worker.Id3);
Console.WriteLine("Want to get: ModelActor1 ModelActor2");
}
除了'Main',我在這裏看不到'static's。 (我不確定它是否相關,但你似乎在標題/初始敘述中做了很多) –
@Damien_The_Unbeliever懶惰構造函數的內容不能包含課堂實現。所以... static –