Is it possible to create a C# 'pointer' to a DateTime object?
Is it possible to create a C# pointer to a DateTime object? I'm trying to d开发者_如何学编程o this:
DateTime Event1 = DateTime.Now;
DateTime Event2 = DateTime.Now.AddYears(10);
DateTime EventPointer; // A Pointer?
if (something)
{
EventPointer = Event1;
}
else
{
EventPointer = Event2;
}
EventPointer.DoSomething? // Something that would change the value of Event1/2 variable.
Not directly, but you can wrap it around a class:
Wrapper w1 = new Wrapper { TheDate = DateTime.Now };
Wrapper w2 = new Wrapper { TheDate = DateTime.Now.AddYears(10) };
Wrapper w;
if (something)
{
w = w1;
}
else
{
w = w2;
}
w.DoSomething();
class Wrapper
{
public DateTime TheDate { get; set; }
public void DoSomething()
{
}
}
DateTimes are value types which unlike reference types everytime you assign its value to another variable their value is copied.
A DateTime
is a value type, when you assign it the value is copied. However, methods can take a reference to a value type using the ref
keyword. Your EventPointer.DoSomething would take a DateTime as reference. Here's a simple example of how you might be able to apply it.
var date = DateTime.Today;
MakeMinValue(ref date);
Console.Out.WriteLine("date = {0}", date);
public void MakeMinValue(ref DateTime dateTime)
{
dateTime = DateTime.MinValue;
}
This will only work with a method parameter.
- You can't use pointers in managed code unless you use
unsafe
. I'd advise against it. - DateTimes are immutable. The only thing you can do to modify a variable of type DateTime is to reassign to it.
You can do something close to what you want, but in general it's not a good idea to do this:
DateTime event1 = new DateTime(2011, 10, 11);
DateTime event2 = new DateTime(2021, 10, 11);
Action<DateTime> eventPointer; // A Pointer?
if (true)
{
eventPointer = x => { event1 = x; };
}
else
{
eventPointer = x => { event2 = x; };
}
eventPointer(new DateTime(2016, 10, 11));
Console.WriteLine(event1.ToString(CultureInfo.InvariantCulture));
Console.WriteLine(event2.ToString(CultureInfo.InvariantCulture));
Result:
10/11/2016 00:00:00 10/11/2021 00:00:00
I think it is a better idea is to find another way to solve your problem.
Pointers, as you are thinking of them, don't exist in managed C# code. You might want to look into out
and ref
parameters if you need to pass a DateTime and have the original value change. Since DateTimes are structs (value type) they are always copied instead of passed by reference, unless you specifically use an out
or ref
parameter.
You can replace type of EventPointer
, Event1
and Event2
types from DateTime
type to DateTime?
. It makes EventPointer's type nullable reference type.
DateTime? Event1 = DateTime.Now;
DateTime? Event2 = DateTime.Now.AddYears(10);
DateTime? EventPointer;
if (condition)
{
EventPointer = Event1;
}
else
{
EventPointer = Event2;
}
EventPointer.Value //.DoSomething
精彩评论