我有一个像这样的日期时间变量:
DateTime myDate=DateTime.Now; // result is like this: 8/2/2020 12:54:07 PM
Run Code Online (Sandbox Code Playgroud)
我想得到myDate这样的变量
DateTime getOnlyDate=myDate.Date;
Run Code Online (Sandbox Code Playgroud)
我想myDate.Date;通过反射获得属性值,如何Date通过反射获得属性值?经过反思,我做了这样的事情:
PropertyInfo myDate = typeof(DateTime).GetProperty("Date");
Run Code Online (Sandbox Code Playgroud)
但我不知道如何 myDate.Date;通过反射来请求价值。提前致谢
检索到 后PropertyInfo,您可以使用 获取值PropertyInfo.GetValue,并传入“您想要从中获取属性的事物”(或null对于静态属性)。
这是一个例子:
using System;
using System.Reflection;
class Program
{
static void Main()
{
DateTime utcNow = DateTime.UtcNow;
PropertyInfo dateProperty = typeof(DateTime).GetProperty("Date");
PropertyInfo utcNowProperty = typeof(DateTime).GetProperty("UtcNow");
// For instance properties, pass in the instance you want to
// fetch the value from. (In this case, the DateTime will be boxed.)
DateTime date = (DateTime) dateProperty.GetValue(utcNow);
Console.WriteLine($"Date: {date}");
// For static properties, pass in null - there's no instance
// involved.
DateTime utcNowFromReflection = (DateTime) utcNowProperty.GetValue(null);
Console.WriteLine($"Now: {utcNowFromReflection}");
}
}
Run Code Online (Sandbox Code Playgroud)