微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#泛型 – 类型参数的约束

我正在尝试构建一个使用C#的泛型功能的工厂方法.

在这个工厂方法中,我想将它约束到一些特定的类,所有这些类都没有认的构造函数.

这是我的例子.有人可以告诉我是否可以运行它?

public class AbstractClass {
    //this abstract class does not have a default constructor,nor its subclasses
    public AbstractClass(SomeClassName obj) {
        //use obj for initialization
    }
}

//this factory class should create objects of type T that inherit 
//from AbstractClass and invoke the non-default constructor
public class FactoryClass {
    public static T Buildobject<T> (SomeClassName obj) where T: AbstractClass {
        return new T(obj); //does not work?!?!?!
    }
}


//Edit: ANSWER!!!
public static T Buildobject<T>(SomeClassUsedForTheConstructor item) where T : SomeAbstractClass { 
return (T) Activator.CreateInstance(typeof (T),item); 
}

解决方法

查看 Type类和GetConstructor.获得ConstructorInfo对象后,使用Invoke方法.
var x = typeof(T);
var t = x.GetConstructor(new[] {obj.GetType()});
object u = t.Invoke(<inputs>);

原文地址:https://www.jb51.cc/csharp/101046.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐