我可以将类型参数传递给* .xaml.cs类吗?

时间:2013-04-23 18:42:23

标签: c# generics partial-classes type-parameter

我想将一个类型参数传递给我的* .xaml.cs文件。 C#代码如下所示:

public partial class Filter<T> : Window where T : IFilterableType
{
    private readonly IEnumerable<T> _rows;
    public Filter(IEnumerable<T> rows)
    {
        this._rows = rows;
    }
}

由于这是一个部分类,并且由于Visual Studio生成了该类的其他部分,因此我担心当Visual Studio重新生成部分类的其他部分时,我的类型参数<T>将被删除。到目前为止,在我的测试中,这还没有发生,但我想确定。

我可以将类型参数传递给* .xaml.cs文件吗?

如果没有,我的* .xaml.cs类是否还有其他方法可以拥有某些泛型类型的私有列表?我会尝试类似下面的内容,但当然不会编译。

public partial class Filter : Window
{
    private IEnumerable<T> _rows;
    public Filter() { }

    public void LoadList(IEnumerable<T> rows) where T : IFilterableType
    {
        this._rows = rows;
    }
}

2 个答案:

答案 0 :(得分:0)

很遗憾,在XAML

中,您所请求的选项都不可用

答案 1 :(得分:0)

这是另一种选择。我已经得到了这个工作,但它肯定是丑陋的代码。我使用一个简单的object变量来保存通用列表。我使用具有约束类型参数的方法来确保我使用IFilterableType接口。我还检查了DisplayList方法中的类型,以确保我使用IFilterableType的正确实现。

如果我使用FilterB而不是FilterA来调用this.DisplayList,我将获得异常。这是我能想到的最好的解决方案。

public partial class Filter : Window
{
    public Filter()
    {
        List<FilterA> listA = new List<FilterA>();
        this.SetList<FilterA>(listA);
        this.DisplayList<FilterA>();
    }

    public interface IFilterableType { string Name { get; } }
    public class FilterA : IFilterableType { public string Name { get { return "A"; } } }
    public class FilterB : IFilterableType { public string Name { get { return "B"; } } }


    private object _myList;
    private Type _type;

    public void SetList<T>(List<T> list) where T : IFilterableType
    {
        this._myList = list;
        this._type = typeof(T);
    }

    public void DisplayList<T>() where T : IFilterableType
    {
        if (this._myList is List<T>)
            this.DataContext = (List<T>)this._myList;
        else
            throw new ArgumentException();
    }
}
相关问题