将方法分配给通用属性

时间:2012-07-27 20:10:53

标签: c# oop generics .net-4.0 delegates

我正在尝试设计一个足够灵活的类来绘制有关不同类型数据的数据。我是C#中的OOP的新手,所以我在尝试使用泛型,代理和类的一些组合来实现这一目标。

这是我到目前为止所写的课程:

using System;
using System.Collections.Generic;

namespace Charting
{
    public class DataChart<T>
    {
        public Func<T, object> RowLabel { get; set; }
    }
}

以下是我试图称之为:

var model = new DataChart<MyClass>()
{
    RowLabel = delegate(MyClass row)
    {
        return String.Format("{0}-hello-{1}", row.SomeColumn, row.AnotherColumn);
    }
};

这种方法的问题是我必须显式地转换 RowLabel 发出的对象。我希望我能以某种方式使输出类型成为泛型并为其添加约束,如下所示:

    public class DataChart<T>
    {
        // The output of the RowLabel method can only be a value type (e.g. int, decimal, float) or string.
        public Func<T, U> RowLabel where U : struct, string { get; set; }
    }

这可能吗?如果是这样,我该怎么做?提前谢谢!

1 个答案:

答案 0 :(得分:1)

你可以做一些

首先,对输出进行泛化:只需在类中添加另一个类型参数。

public class DataChart<T, U>
{
  public Func<T, U> RowLabel  { get; set; }
}

但是你提到的那些类型限制没有意义。类型约束是“和”-ed,而不是“或”-ed。 string不是struct,因此您无法将其限制为特定的类型组合。如果你不受约束,它仍然可以工作,尽管你会失去一些编译时的安全性。

编辑:此外,无论如何,事实证明你无法将string指定为类型参数。这是一个密封的课程!拥有只接受密封类类型的泛型将是毫无意义的,编译器会阻止它。

相关问题