简体   繁体   English

generics class 实现 IEnumerable 中的 Get 和 Set 方法

[英]Get and Set methods in generics class implementing IEnumerable

I have a class implementing generics and IEnumerable我有一个 class 实现 generics 和 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).我想在 set 方法中实现一些逻辑(或者以其他方式,每当我的数据发生变化时)。 Without commenting the line Data = value I get StackOverflow.没有评论Data = value行,我得到了 StackOverflow。 With the line: Data = value commented out at least the instantiation works, but only when using a string as generics:使用以下行: Data = value注释掉至少实例化有效,但仅当使用字符串作为 generics 时:

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

However, as soon as I try to plug into my own object:然而,一旦我尝试插入我自己的 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?我收到“无法读取内存”如何正确定义 get/set 方法,以便在实例化时可以使用MyOwnObjectType而不是 T/string?

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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