【问题标题】:Accessing property访问属性
【发布时间】:2015-11-03 07:45:38
【问题描述】:
public class SomeClass<TElement>
{
    TElement _element;

    public void SomeFunction()
    {
        _element.Property = someValue;
    }

    public TElement Element 
    {
        get 
        {
            return _element;
        }
        set 
        {
            _element = value;
        }
    }
}

这基本上是我想做的。此类中的“TElement”将始终是从包含“Property”的类继承的类。我希望能够访问“Property”并对其进行修改,并且我希望“SomeClass”能够公开类型为“TElement”的属性。当我尝试这样做时,我无法访问属性,因为“TElement 不包含...的定义”。

如果我不使用“TElement”,但直接使用上述类,我不知道如何使“Element”属性根据实例显示为不同的类型。

我是不是走错路了?谁能指出我获得这种功能的正确方向? 谢谢

【问题讨论】:

  • 因为当使用这个 calss 时,它永远不会是基类,如果我没记错的话,在这种情况下我必须对属性进行大量转换才能访问不在的属性基类。

标签: c# class types


【解决方案1】:
public class SomeClass<TElement> where TElement : IProperty
{
    TElement _element;

    public void SomeFunction()
    {
        _element.Property = someValue;
    }

    public TElement Element 
    {
        get 
        {
            return _element;
        }
        set 
        {
            _element = value;
        }
    }
}
public interface IProperty
{
    SomeType Property { get; }
}

【讨论】:

    【解决方案2】:
    public class SomeClass<TElement>
        where TElement : YourBaseClass
    { ... }
    

    这叫做generic type constraint:

    在泛型类型定义中,where 子句用于指定可用作泛型声明中定义的类型参数的实参的类型的约束

    【讨论】:

      【解决方案3】:

      你需要一个泛型类型约束来表达TElement必须有这个Property:https://msdn.microsoft.com/en-us/library/Bb384067.aspx

      例如:

      public interface IHaveProperty
      {
          string Property { set; }
      }
      
      public class SomeClass<TElement> where TElement : IHaveProperty
      {
      
          TElement _element;
      
          void SomeFunction() 
          {
               // the generic constraint on TElement says that 
               // TElement must implement IHaveProperty, so you can
               // access Property here.
               _element.Property = string.Empty;
          }
      
      }
      

      【讨论】:

      • 这和只有SomeClass 和IHaveProperty _element; 一样吗(即没有泛型)?
      • @Default 否,至少在您公开公开 TElement 属性时不会。一个使用泛型“泛型”地公开一些功能:这个类的用户仍然可以从TElement 调用任何方法或访问任何属性,而无需强制转换/拆箱。
      猜你喜欢
      • 2017-03-16
      • 2013-12-23
      • 2013-07-11
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多