我有一个像这样的日期时间变量:
DateTime myDate=DateTime.Now; // result is like this: 8/2/2020 12:54:07 PM
我想得到这样的myDate
变量
DateTime getOnlyDate=myDate.Date;
我想myDate.Date;
通过反射来获取Date
属性值?用反射我做这样的事情:
PropertyInfo myDate = typeof(DateTime).GetProperty("Date");
但是我不知道我该如何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}");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句