检查对象参数是否包含日期时间

时间:2019-04-10 19:44:46

标签: c# .net

我有一个带有对象参数的方法,因此可以通过不同的调用方法以不同的方式使用它。在该方法内部,我需要检查对象的第一个参数是否为date(如果未设置今天的日期)。

public void CreateNew(FileModel data, Object otherParams = null)
{
     DateTime portDate = DateTime.Now;
     if (otherParams is DateTime)
         portDate = (DateTime)otherParams;

    //In case 1 portDate is portDate value and in case 2 portDate value id 
    //DateTime.Now() even though portDate contains a value.
}

我通过以下两种方式将对象传递给该方法。

CreateNew(fileData,new {portDate=portDate});
CreateNew(fileData,new {portDate=portDate,countries=countries});

以上代码适用于第一种情况,但不适用于第二种情况,并且portDate始终是今天的日期。那么,如何拥有通用的日期检查案例来正确处理这两个案例?

3 个答案:

答案 0 :(得分:3)

您可以使用dynamic代替Object,然后检查

if (otherParams?.portDate is DateTime)
{ ...}

尽管我同意这样的评论,即您似乎以错误的方式使用了匿名类。如果您知道要接收的内容,请创建一个具有DateTime portDate的真实类,以便您肯定知道。

答案 1 :(得分:1)

您可以查看对象的所有属性,并检查其中之一是否为日期时间

    object example  = new {si= DateTime.Now, no= "no"}; //object example

    var typevar  = example.GetType().GetProperties(); //get all te props
    //lets loop all the props
    foreach(var i in typevar){
       if(i.PropertyType == typeof(System.DateTime)){
         //if is DateTime well write the name of prop with i.Name 
         Console.WriteLine("The propiertie {0} is date time", i.Name);
       }
    }

它也适用于动态参数

答案 2 :(得分:1)

您的问题表明,如果otherParams不是DateTime,您将使用DateTime.Now。这表明如果otherParams不是DateTime,则不会使用它。

如果是这种情况,那么更好的签名可能是:

public void CreateNew(FileModel data, DateTime? portDate = null)

这使调用者清楚地知道portDate应该是DateTime,但是它是可选的。然后,您可以执行以下操作:

portDate = portDate ?? DateTime.Now;

因此,如果没有任何价值,它将被替换为DateTime.Now

如果有不同的调用方式,则可以根据调用方式提供不同的重载。

您还可以添加:

public void CreateNew(FileModel data, Countries countries, DateTime? portDate = null)

如果任何一个都可以为null,但它们都不应该都为null,则可以创建反映该签名的签名,然后让每个签名都调用private方法来处理null。这样,您就可以更清晰地传达期望。

如果其他地方需要调用类似的方法,但是第二个参数可能完全不同(不是日期),那么最好创建一个不同的方法。如果参数的类型为object,并且一种可能是DateTime,并且至少存在其他一种正确的类型,则调用者无法知道应该传递什么。例如,他们可以致电:

CreateNew(someFileModel, new List<string>());

...,它将编译,但是您的方法对该List<string>没有任何用处,甚至可能会引发异常。类型安全性非常有价值,因为它使我们能够预先获得所有正确的信息。如果我们没有传递正确的类型,该代码甚至不会编译。我们不希望我们的代码编译,如果可以避免的话,会给我们一个运行时错误。

作为一个广泛的指导原则,如果类型根本不重要,则仅应使用object。您可以将对象传递到String.Format,因为在大多数情况下,它将仅调用ToString(),因此类型无关紧要。在90%或更多的时间(我说接近99.5%)中,类型很重要。如果我们装箱后觉得需要使用dynamicobject,那么我们应该退后一步,尝试从该角上取消涂漆。

相关问题