根据类型参数创建对象 [英] Creating an object based on a type parameter

查看:56
本文介绍了根据类型参数创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题要摆在我面前.我有一个方法CreateInternals()的类A. CreateInternals()任务之一是创建一个新的B对象. B对象有几种类别(B1B2B3 ...),但是它们都实现了接口IBable.应该将要创建的B对象的类型传递给A.CreateInternals().
现在我知道我可以让CreateInternals接受System.Type参数

I am having a problem bending my mind to situation. I have a class A with a method CreateInternals(). One of CreateInternals() tasks is to create a new B-object. There are several classes of B-object (B1, B2, B3...) but they all implement the interface IBable. The type of B object to be created is supposed to be passed to A.CreateInternals().
Now I know that I could just have CreateInternals accept a System.Type parameter

public void CreateInternals(System.Type BToMake)
{
	ConstructorInfo cInfo = type.GetConstructor(argTypes);
	IBable internalB = (IBable)cInfo.Invoke(new object[]());
	...
}


并以适当的类型进行调用


and call it with the appropriate type

A.CreateInternals(typeof(B2));



但是,这不会阻止我用无效的类型
调用CreateInternals



However, this would not prevent me from calling CreateInternals with an invalid type

A.CreateInternals(typeof(C));


而且直到运行时我都看不到错误.

有没有办法让编译器限制CreateInternals 仅接受实现IBableBToMake 参数?像


and I would not see the error until runtime.

Is there a way to get the compiler to restrict CreateInternals to only accept BToMake parameters that implement IBable? Something like

public voide CreateInternals(System.Type BToMake where BToMake is IBable) {...}


我有一种奇怪的感觉,我可以使用泛型来做到这一点,但是我想我一直盯着这个问题已经很长时间了,以至于我已经绞尽脑汁,答案就不会出现.

任何帮助将不胜感激.


I have the strange feeling that I can do this using generics, but I think I''ve been staring at the problem for so long that I have brain-lock and the answer just won''t come.

Any help would be appreciated.

推荐答案

2种方法.如果您不想将对象的实例作为参数处理:
2 ways of doing it. If you prefer NOT having to deal with instances of your object as parameters:
public void CreateInternals<T>() where T:IBable
{
    Type theTypeIs = typeof(T);
..
..
..
}

CreateInternals<yourclassname>();
</yourclassname>



否则,如果您希望将实例作为参数传递:



Otherwise, if you prefer passing instances as parameters:

public static void CreateInternals<T>(T BToMake ) where T:IBable
{
    Type theTypeIs = BToMake.GetType();
..
..
..
}

CreateInternals(someInstanceImplementingYourInterfaceIBable);


这篇关于根据类型参数创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆