如何使用TypeConverters将System.Datetime转换为自定义类型

时间:2022-11-05 16:32:37

For some reason I need to cast/convert a DateTime into one of many custom objects

出于某种原因,我需要将DateTime转换/转换为许多自定义对象之一

This proves to be very difficult to do in a nice generic fashion.

事实证明这很难以通用的方式进行。

I am thinking of implementing an extension method on object or perhaps extending DateTimeConverter.

我正在考虑在对象上实现扩展方法或者可能扩展DateTimeConverter。

But then what would be the generic way to handle this, I have an object and a destination type and at the moment I am using System.ConvertTo(..) but this is clearly limited because it only supports converting to .NET types and cant be extended.

但那么处理这个的通用方法是什么,我有一个对象和一个目标类型,目前我正在使用System.ConvertTo(..),但这显然是有限的,因为它只支持转换为.NET类型和不能延长。

Any ideas?

1 个解决方案

#1


You could add a constructor for your TimeStamp that takes DateTime as a parameter.

您可以为TimeStamp添加一个构造函数,该构造函数将DateTime作为参数。

public class TimeStamp
{
   public TimeStamp(DateTime dateTime, ...)
   {
    // Your code here to convert from dateTime to TimeStamp
   }
}

Then later ...

然后......

 DestType Convert<DestType>( Object linqResult )   
 {
  DestType result;
  if( linqResult is DateTime && DestType is TimeStamp )
  {
   DateTime dbTime = linqResult as DateTime;
   result = new TimeStamp( dbTime );
  }
  ...
  return result;
 }

You could probably even extend this with all kinds of reflection and constructors etc. But if you want to base one object off of another (like a time stamp from a date time) a constructor seems natural.

您甚至可以使用各种反射和构造函数等扩展它。但是如果您想要将一个对象基于另一个(如日期时间的时间戳),构造函数似乎很自然。

Hope this helps, TJB

希望这会有所帮助,TJB

#1


You could add a constructor for your TimeStamp that takes DateTime as a parameter.

您可以为TimeStamp添加一个构造函数,该构造函数将DateTime作为参数。

public class TimeStamp
{
   public TimeStamp(DateTime dateTime, ...)
   {
    // Your code here to convert from dateTime to TimeStamp
   }
}

Then later ...

然后......

 DestType Convert<DestType>( Object linqResult )   
 {
  DestType result;
  if( linqResult is DateTime && DestType is TimeStamp )
  {
   DateTime dbTime = linqResult as DateTime;
   result = new TimeStamp( dbTime );
  }
  ...
  return result;
 }

You could probably even extend this with all kinds of reflection and constructors etc. But if you want to base one object off of another (like a time stamp from a date time) a constructor seems natural.

您甚至可以使用各种反射和构造函数等扩展它。但是如果您想要将一个对象基于另一个(如日期时间的时间戳),构造函数似乎很自然。

Hope this helps, TJB

希望这会有所帮助,TJB