我希望说:
public void Problem(DateTime optional = DateTime.MaxValue)
{
}
但是编译器抱怨DateTime.MaxValue不是编译时常量。
DateTime.MinValue很容易,只需使用default(DateTime)
另请参阅“如何在C#中将参数默认为Guid.Empty?”
我不想使用方法重载,因为我尝试驯服的方法有101个参数!
我希望说:
public void Problem(DateTime optional = DateTime.MaxValue)
{
}
但是编译器抱怨DateTime.MaxValue不是编译时常量。
DateTime.MinValue很容易,只需使用default(DateTime)
另请参阅“如何在C#中将参数默认为Guid.Empty?”
我不想使用方法重载,因为我尝试驯服的方法有101个参数!
我会用类似下面的方法来替代这个:
public void Problem(DateTime? optional = null)
{
DateTime dateTime = optional ?? DateTime.MaxValue
// Now use dateTime
}
DateTime dateTime = optional ?? DateTime.MaxValue;
。 - Jeppe Stig Nielsenpublic void Problem()
{
Problem(DateTime.MaxValue);
}
public void Problem(DateTime optional)
{
// do your stuff here.
}
我不熟悉C#4.0,但在C#3.5中,我会使用重载;
public void Problem()
{
Problem(DateTime.MaxValue);
}
public void Problem(DateTime dt)
{
}
你可以使用以下任意一种方式调用它:
Problem(); //defaults to maxvalue
Problem(myDateTime); //uses input value
编辑: 回应一些评论:
public class FooBar
{
public bool Problem()
{
//creates a default person object
return Problem(new Person());
}
public void Problem(Person person)
{
//Some logic here
return true;
}
}
public class Person
{
public string Name { get; private set; }
public DateTime DOB { get; private set; }
public Person(string name, DateTime dob)
{
this.Name = name;
this.DOB = dob;
}
/// <summary>
/// Default constructor
/// </summary>
public Person()
{
Name = "Michael";
DOB = DateTime.Parse("1980-07-21");
}
}
DateTime.MaxValue
不是编译时常量;它实际上是一个只读字段,在运行时由静态构造函数初始化。这里的区别变得非常关键。可选参数需要编译时常量,因为它们直接将值嵌入到代码中。DateTime?
并传递 null
,然后在方法中将 null
解释为 DateTime.MaxValue
。default(DateTime)
,但是配合后续的内部检查,这完全是一个有效的替代方案...即使使用方式不变,因为给它一个空的 DateTime?
仍然会触发默认值。 - Adam Houldsworth如果您在其中一条评论中提到的方法有很多参数,您可以将它们全部转换为参数类,并使用其属性初始化程序。然后您就不必初始化所有属性,可以在该类的构造函数中将日期设置为 DateTime.MaxValue
。
loadDefault参数值是常量,也就是说,它不能是string.Empty
/Guid.Empty
等。您可以使用方法重载:
void M(int intValue)
{
M(intValue, Guid.Empty);
}
void M(int intValue, Guid guid)
{
//do something
}