有没有办法引用继承抽象类的类(即 Type
)?
class abstract Monster
{
string Weakness { get; }
string Vice { get; }
Type WhatIAm
{
get { /* somehow return the Vampire type here? */ }
}
}
class Vampire : Monster
{
string Weakness { get { return "sunlight"; }
string Vice { get { return "drinks blood"; } }
}
//somewhere else in code...
Vampire dracula = new Vampire();
Type t = dracula.WhatIAm; // t = Vampire
对于那些好奇的人......我在做什么:我想知道我的网站上次发布是什么时候。
.GetExecutingAssembly
工作得很好,直到我从我的解决方案中取出 dll。之后,BuildDate
始终是实用程序 dll 的最后构建日期,而不是网站的 dll。namespace Web.BaseObjects
{
public abstract class Global : HttpApplication
{
/// <summary>
/// Gets the last build date of the website
/// </summary>
/// <remarks>This is the last write time of the website</remarks>
/// <returns></returns>
public DateTime BuildDate
{
get
{
// OLD (was also static)
//return File.GetLastWriteTime(
// System.Reflection.Assembly.GetExecutingAssembly.Location);
return File.GetLastWriteTime(
System.Reflection.Assembly.GetAssembly(this.GetType()).Location);
}
}
}
}
最佳答案
使用 GetType()
方法。它是虚拟的,所以它的行为是多态的。
Type WhatAmI {
get { return this.GetType(); }
}
关于c# - 从抽象类引用继承类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4055559/