简体   繁体   中英

C# how to make a class that behave like Nullable<T>

Given the code:

public class Filter<T>
{
    private bool selected = false;
    public bool Selected { get { return selected; } }

    private T value;
    public T Value { get{ return this.value; } set { this.value = value; selected = true; }
}     

public class Test
{
    public void filter()
    {
        DateTime a= new DateTime();
        Nullable<DateTime> b = new DateTime(); //Work Like a Charm
        Filter<DateTime> c = new DateTime(); //Dosent Work
    }
}

In Nullable<T> the new DateTime() can be assigned directly into the variable. In my class, it doesn't work. I want to understand what I'm missing.

I think that is something simple. But I couldn't put it on words to find the answer.

You have to implement implicit operators :

public static implicit operator Filter<T>(T value)
{
    return new Filter<T>() { Value = value };
}

An implicit operator will allow you to cast the types without explicitly writing Filter<T> filter = (Filter<T>)value; (explicit cast), but rather only Filter<T> filter = value; (implicit cast).

You need to use an implict conversion operator:

See: Implicit cast operator and the equality operator

This allows you to write code to construct your custom type from another type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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