简体   繁体   中英

How get property value with reflection in C#

I have a date-time variable like this:

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

and I want to get myDate variable like this

DateTime getOnlyDate=myDate.Date; 

and I want to get myDate.Date; with reflection how can I get Date property value with reflection? with reflection I do something like this:

PropertyInfo myDate = typeof(DateTime).GetProperty("Date");

but I don`t know how can I request myDate.Date; value with reflection. thanks in advance

Once you've retrieved the PropertyInfo , you fetch the value with PropertyInfo.GetValue , passing in "the thing you want to get the property from" (or null for a static property).

Here's an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM