将具有类型约束定义的特定父类的子元素作为参数传递

时间:2013-04-18 22:59:50

标签: c# parent argument-passing type-constraints

我正在尝试创建一个方法,在该方法中传递一个必须实现需要类型约束的特定类的参数。 我希望能够设置泛型类型的costraint参数。

这是我的问题的一个场景:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class TestClass
    {
        public void TestMethod(SharedClass<???> obj)
        {
            //DoSomething
        }

        public void Main()
        {
            TestMethod(new FixedClass1()); //Work if TestMethod(SharedClass<FixedInterface1> obj)
            TestMethod(new FixedClass2()); //Work if TestMethod(SharedClass<FixedInterface2> obj)
        }
    }

    public class FixedClass1 : SharedClass<FixedInterface1> { }

    public class FixedClass2 : SharedClass<FixedInterface2> { }

    public class SharedClass<T> where T : class { }

    public interface FixedInterface1 { }

    public interface FixedInterface2 { }

}

感谢所有回复。

1 个答案:

答案 0 :(得分:0)

这是你想要做的......

public void TestMethod<T>(SharedClass<T> obj) where T : class
{
    //DoSomething
}