繁体   English   中英

接受任何参数的方法,遍历它以搜索 DateTime 变量,更改它们并在 C# 中返回新的 object

[英]Method that accepts any parameter, loop through it for search into DateTime variables, change them and return a new object in C#

我想写一个 function ,我可以在其中传递任何类型的参数(主要是 IQueryable 或 List<>)+ 本地时区(“中央标准时间”等)。

Function 转换时间:

public DateTime? LocalTimeConvert(string locationTimeZone, DateTime? dateTimeUtc)
{
    var offset = TimeZoneInfo.FindSystemTimeZoneById(locationTimeZone);
    var timeZoneCorrection = TimeZoneInfo.ConvertTime(dateTimeUtc.Value, offset);
    return timeZoneCorrection;
}

我已经搜索了数百个 stackoverflow 主题,但我似乎有点缺乏 C# 知识。

到目前为止,我写了这个:

public static void LocalTime<T>(T value, string locationTimeZone) 
{
    if(value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(List<>))
    {
        IList<T> collection = (IList<T>)value;
        foreach (var element in collection)
        {
            var properties = element.GetType().GetProperties();
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(DateTime))
                {
                    
                }
            }
        }
    }
}

这是我尝试做的T 值将是List<>的部分。 谁能与我分享一篇文章,我可以在其中阅读有关如何返回与我得到的相同类型的列表的文章? 另外,在我使用typeof(DateTime)获得属性之后,我应该将属性转换为DateTime然后使用LocalTimeConvert吗?

你可以做类似的事情:

public IEnumerable<T> LocalTime<T>(IEnumerable<T> value, string locationTimeZone)

因此,您会收到一个列表(无论项目是哪种类型),完成后您可以返回相同的列表。

编辑:对于 DateTime 的东西,你可以使用 DateTimeOffset 类型吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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