简体   繁体   中英

Get and Set methods in generics class implementing IEnumerable

I have a class implementing generics and IEnumerable

public class MyEnumClass<T> : IEnumerable<MyEnumClass<T>>
{
   public T Data
   {
     get { return this.Data; } 
     set 
        {
          Data = value;
        }
    }

 public MyEnumClass(T data)
 {
   Data = data;
  }
}

I would like to implement some logic inside the set method (or in some other way, whenever my Data gets changed). Without commenting the line Data = value I get StackOverflow. With the line: Data = value commented out at least the instantiation works, but only when using a string as generics:

var foo = new MyEnumClass<string>("Foo");

However, as soon as I try to plug into my own object:

var foo = new MyEnumClass<MyOwnObjectType>(InstanceOfMyOwnObjectType);

I get "Unable to read memory" How can I properly define get/set methods so that I could use MyOwnObjectType instead of T/string when instantiating?

you need to create an explicit backing field

public class MyEnumClass<T> : IEnumerable<MyEnumClass<T>>
{
    T m_data;
    public T Data
    {
        get { return this.m_data; } 
        set 
        {
            m_data = value;
        }
    }

    public MyEnumClass(T data)
    {
            Data = data;
    }
}

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