gpt4 book ai didi

c# - C#中如何通过反射获取属性值

转载 作者:行者123 更新时间:2023-12-02 19:19:49 26 4
gpt4 key购买 nike

我有一个这样的日期时间变量:

DateTime myDate=DateTime.Now; // result is like this: 8/2/2020 12:54:07 PM

我想像这样获取 myDate 变量

DateTime getOnlyDate=myDate.Date; 

我想通过反射获取 myDate.Date;如何通过反射获取 Date 属性值?经过反射(reflection),我做了这样的事情:

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}");
}
}

关于c# - C#中如何通过反射获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63213998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com