一个类中有静态变量,在程序中能不能使用反射动态取得这个静态变量的值?

hanbaojun 2004-12-10 09:41:12
一个类中有静态变量,在程序中能不能使用反射,动态取得这个静态变量的值?

谢谢!
...全文
474 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
greennetboy 2004-12-11
  • 打赏
  • 举报
回复
感觉没必要
hanbaojun 2004-12-10
  • 打赏
  • 举报
回复
和这个贴子结合起来:
http://community.csdn.net/Expert/topic/3632/3632317.xml?temp=7.177371E-02
brightheroes 2004-12-10
  • 打赏
  • 举报
回复
为什么一定要使用反射?
hanbaojun 2004-12-10
  • 打赏
  • 举报
回复
我的是意思是在程序里动态呀,也就是说程序执行时类名是变化的,怎样根据这个类名取得这个类中的这个静态变量的值。
jiezhi 2004-12-10
  • 打赏
  • 举报
回复
静态变量你还需要用反射取值么?
jimh 2004-12-10
  • 打赏
  • 举报
回复
应该可以,我没试过
SAsura 2004-12-10
  • 打赏
  • 举报
回复
可以,我用过,和普通的变量一样,反射是忽略object instance的参数值,你随便传吧,只要是这个class的实例就可以,也可以用null
juqiang 2004-12-10
  • 打赏
  • 举报
回复
Type[] typelist = asm.GetTypes();
string s = "";
上面的这两行,只是为了设置断点用的,没有实际意义。
juqiang 2004-12-10
  • 打赏
  • 举报
回复
这是完整的代码,你直接建一个console工程,把代码copy进去,修改命名空间为ConsoleApplication3即可。

using System;
using System.Reflection;

namespace ConsoleApplication3
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Assembly asm = Assembly.GetExecutingAssembly();
Type[] typelist = asm.GetTypes();
Type t = asm.GetType("ConsoleApplication3.Class2");
object obj = Activator.CreateInstance(t);
FieldInfo fi = t.GetField("Hello");
object hello = fi.GetValue(obj);
string s = "";
}
}

class Class2
{
public static string Hello = "World";
}
}
jeffandjeff 2004-12-10
  • 打赏
  • 举报
回复
举个实际你想应用的例子看看到底要干吗

110,567

社区成员

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

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

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