// 假设这个是一个静态类.一切成员都是静态的
public static class A {
public static string strings = null; public static void SetString(string _s) {
strings = _s;
} public static string GetString() {
// TODO: 判断该方法的返回值是否为空,为空怎么做,不为空怎么做
return strings;
}
}// 类 B 不能判断 类A的GetString()返回值是否为空,也不能改变GetString()的参数.就是
class B {
string strTest = "如果这句话没有被覆盖.请保留.";
b() {
strTest = a.GetString();
}
}能否用反射机制来做?在调用 类A的GetString()方法 之前 先获取到调用 类A的GetString()方法 的对象?
strTest = a.GetString(); // 如果a.GetString(); 里面捕获到异常,如果不处理,这个返回值是null吗?
楼主的要求是更进了一步, 取得调用该静态方法的对象/方法,
可以看看 system.assembly.reflect(拼写好象不对?) 空间的类/方法 是否提供类似 getcallingclass,getcallingobject,getcallingmethod 的功能.个人认为可能可以取到 class/method 这两个都是代码级的问题, 是反射 层面的, callingobject 更象数据级的问题,不属于反射层面的.程序运行时 代码段 与数据段是存储在不同内存区域中的, 如果类成员中没有定义 传递调用类/方法的成员或attribute 从反射应该取不到calling object.
public static class A {
private static string strings = null;
public static string Strings
{
get
{
//如果strings为空
if(String.IsNullOrEmpty(strings))
{
//这里写逻辑代码
return string.Empty;
}
else
{
return strings;
}
}
set{strings=value;}
}
================
不知道为什么要有这个限制?
也不太清楚到底要实现什么功能?不过我把你写的A类通过属性的方式写出来了,你那种写法是C++\Java中写法。
Object obj = Activor.CreateInstance(typeof(A));
strTest=a.GetType().GetMethod("GetString").Invoke(a,null);
public static string strings = null;
既然已经是全局静态,还整那么多事情干吗?无论你在那里用String.isNullorEmpty()都成6楼滴,也算是标准的代码,可以参考呵呵,看lz自己的那个代码,我感觉你不像是在写c#,而是在写delphi的属性
class B
{
string strTest = "如果这句话没有被覆盖.请保留."; b()
{
strTest = a.GetString() ?? strTest;
}
}
public static class A
{
public static string strings = null; public static string Strings
{
get
{
// TODO: 判断该方法的返回值是否为空,为空怎么做,不为空怎么做
return strings;
}
set
{
strings = value;
}
}
}// 类 B 不能判断 类A的GetString()返回值是否为空,也不能改变GetString()的参数.就是
class B
{
string strTest = "如果这句话没有被覆盖.请保留."; B()
{
strTest = A.Strings ?? strTest;
}
}