静态方法如何获取当前类型

moonchnn 2017-02-18 11:49:09
本人使用了多态, 想用反射取当前类型的重载,例:

class C0
{
public static string s = "0";
public static string gets()
{
return s;
}
}

class C1 : C0
{
public new static string s = "1";
}


class C2 : C0
{
public new static string s = "2";
}

想实现

C1.gets(); // 得到1
C2.gets(); // 得到2


本来可以利用this.GetType()取到当前类型, 在C1.gets() 时 this.GetType()会得到C1, C2.gets() 时 this.GetType()会得到C2
再用GetField取s, 就能分别得到1和2了
由于在静态方法不能使用this 就没法写this.GetType()了
要怎么写才能实现呢


...全文
293 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2017-02-19
  • 打赏
  • 举报
回复
typeof(类名)
stherix 2017-02-18
  • 打赏
  • 举报
回复
静态方法是不可能实现多态的 所以这根本不是多态, 你要实现只能每个类里都写一个gets
cheng2005 2017-02-18
  • 打赏
  • 举报
回复
静态方法属于类型,不属于对象,所以没有继承的概念。
Poopaye 2017-02-18
  • 打赏
  • 举报
回复
引用 4 楼 u013478753 的回复:

C1.gets<C1>(); // 得到1
C2.gets<C2>(); // 得到2
不要自欺欺人了,这种写法和你直接把type传进去有区别吗?
moonchnn 2017-02-18
  • 打赏
  • 举报
回复
勉强实现了,但是不完美

class C0
{
    public static string s = "0";
    public static string gets<T>() where T:C0
    {
        return typeof(T).GetField("s").GetValue(null).Tostring();
    }
}

class C1 : C0
{
     public new static string s = "1";
}
 
 
class C2 : C0
{
     public new static string s = "2";
}

C1.gets<C1>(); // 得到1
C2.gets<C2>(); // 得到2
Poopaye 2017-02-18
  • 打赏
  • 举报
回复
你这不叫多态,不提供类名实现不了这个需求

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧