C#泛型静态字段问题 [英] C# generic static field problem

查看:257
本文介绍了C#泛型静态字段问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class base{ public string f1; }

public class Derive1{  }

public class Derive2{  }

void fun1<T>() where T: base
{
   T t = new T();
   string f = t.f1;
}





以上代码效果很好。

让f1更改为静态字段。



我尝试了什么:





above code works well.
let change the f1 to a static field.

What I have tried:

public class base{ public static string f1; }

public class Derive1{  }

public class Derive2{  }

void fun1<T>() where T: base
{   
   string f = T.f1;  // complie error
}





如何让这段代码与静态字段一起使用?



How to make this code works with the static field?

推荐答案

为什么不用这段代码(我在下面修改过的例子)工作?我刚在Linqpad中尝试过它( LINQPad - .NET程序员的游乐场 [ ^ ]);



Why doesn't this code (my altered example below) work? I just tried it in Linqpad (LINQPad - The .NET Programmer's Playground[^]);

void Main()
{
	main m = new main();
	main.f1 = "super";
	fun1<main>();

        Derive1 d = new Derive1();
	fun1<Derive1>();
}
public class main{ static  public string f1; }

public class Derive1: main{  }

public class Derive2 : main{  }

void fun1<T>() where T: main
{   
   string f = main.f1;  // NO compile error
   Console.WriteLine(f);
}





输出结果为:



The output will be :

super
super



这是静态变量的值。您无法以您的方式访问静态。它是CLASS变量而不是实例变量。您的方式是访问实例var。



编辑

更改代码并添加Derive1实例并运行方法那个类也有效。

现在它输出值(超级)两次。


which is the value of the static variable. You cannot access the static the way you were doing it. It is a CLASS variable not an instance variable. Your way was accessing the instance var.

Edit
Altered code and added Derive1 instance and ran method with that class and it works too.
Now it outputs the value (super) twice.


你不能,不能没有反射 - 泛型不支持任何东西静态的。这表明如果你真的必须使用反射来做到这一点。虽然缓慢: C#访问a泛型类中T类型的静态属性 - Stack Overflow [ ^ ]
You can't, not without reflection - generics do not support anything static. This shows how to use reflection to do it, if you really must. Slow though: C# accessing a static property of type T in a generic class - Stack Overflow[^]


这篇关于C#泛型静态字段问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆