我在网上找不到任何能帮我解决这个问题的东西,如果有人能帮你,我会帮你的。
我的函数被赋予了一个属性名和一个对象。使用反射,它返回该属性的值。但是,如果我传递给它一个可以为空的DateTime,它就会给我一个空,而且无论我怎么尝试,我都不能让它工作。
public static string GetPropValue(String name, Object obj)
{
Type type = obj.GetType();
System.Reflection.PropertyInfo info = type.GetProperty(name);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
return obj.ToString();
}
在上面的函数中,obj为空。如何让它读取DateTime?
发布于 2012-06-06 02:34:06
您的代码很好--这将打印一天中的时间:
class Program
{
public static string GetPropValue(String name, Object obj)
{
Type type = obj.GetType();
System.Reflection.PropertyInfo info = type.GetProperty(name);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
return obj.ToString();
}
static void Main(string[] args)
{
var dt = GetPropValue("DtProp", new { DtProp = (DateTime?) DateTime.Now});
Console.WriteLine(dt);
}
}
要避免空值的异常,请将GetPropValue
的最后一行更改为:
return obj == null ? "(null)" : obj.ToString();
发布于 2012-06-06 02:48:43
这对我来说很好..
您确定您的PropertyInfo返回的是非null吗?
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
mc.CurrentTime = DateTime.Now;
Type t = typeof(MyClass);
PropertyInfo pi= t.GetProperty("CurrentTime");
object temp= pi.GetValue(mc, null);
Console.WriteLine(temp);
Console.ReadLine();
}
}
public class MyClass
{
private DateTime? currentTime;
public DateTime? CurrentTime
{
get { return currentTime; }
set { currentTime = value; }
}
}
https://stackoverflow.com/questions/10902731
复制相似问题