创建参数类型的对象
嘿。是否可以有一个方法允许用户传入某种类型的参数并让该方法实例化该类型的新对象?我想做这样的事情:(我不知道泛型是否可行,但试了一下)
public void LoadData<T>(T, string id, string value) where T : new()
{
this.Item.Add(new T() { ID=id, Val = value});
}
上面的方法不起作用,但想法是用户传递他们想要的对象类型实例化,该方法将根据这些参数填充详细信息。 我可以只传递一个 Enum
参数并执行 Switch
并基于该参数创建新对象,但是有更好的方法吗? 谢谢
hey. Is it possible to have a method that allows the user to pass in a parameter of a certain type and have the method instantiate a new object of that type? I would like to do something like this: (I don't know if generics is the way to go, but gave it a shot)
public void LoadData<T>(T, string id, string value) where T : new()
{
this.Item.Add(new T() { ID=id, Val = value});
}
The above doesn't work, but the idea is that the user passes the object type they want to instantiate and the method will fill in details based on those parameters.
I could just pass an Enum
parameter and do a Switch
and create new objects based on that, but is there a better way?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行此操作的唯一方法是添加一个接口,该接口还指定您要设置的参数:
不幸的是,我目前无法进行测试来验证。
The only way to do this would be to add an interface that also specifies the parameters you want to set:
Unfortunately I can't test to verify at the moment.
如果
ID
和Val
属性来自公共基类或接口,则可以约束T
继承该类型。例如:
然后您可以在
T
实例上使用IMyInterface
的所有成员。如果它们只是不同类型中不相关的属性,但碰巧具有相同的名称,则必须使用反射。
另外,您需要从参数列表中删除
T,
。If the
ID
andVal
properties come from a common base class or interface, you can constrainT
to inherit that type.For example:
You can then use all the members of
IMyInterface
onT
instances.If they're just unrelated properties in different types that happen to have the same name, you'll have to use reflection.
Also, you need to remove
T,
from your parameter list.更动态类型的语言可以轻松做到这一点。我确信用 C# 是可能的,只是需要付出更多的努力。可能有一些反射库可以帮助您。
为什么不在调用方法时创建对象呢?你想要做的事情对我来说似乎过于复杂。
A more dynamically typed language could do that with ease. I'm sure its possible with C#, it'll just take more effort. Theres probably some reflection library that will help you here.
Why don't you just create the object when you are calling the method? What you are trying to do seems way overly complex to me.