创建参数类型的对象 [英] Create object of parameter type
问题描述
哎。是否有可能让一个方法允许用户传入某个特定类型的参数并让该方法实例化一个新类型的对象?我想要做这样的事情:(我不知道泛型是否应该走,但给了它一个镜头)
<$ c $ T $ new $($ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ { id,Val = value});
$ b $ p
$ b以上不起作用,但是这个想法是用户传递他们想要实例化的对象类型,并且方法将根据这些参数填充细节。
我可以传递一个Enum
参数并执行Switch
并根据它创建新对象,但有没有更好的办法?
thanks解决方案执行此操作的唯一方法是添加一个也指定您想要的参数的接口set:
public interface ISettable
{
string ID {get;组; }
字符串Val {get;组; }
$ b $ public void LoadData< T>(string id,string value)其中T:ISettable,new()
{
this.Item.Add新的T {ID = id,Val = value});
}
不幸的是我现在无法测试以验证。
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 aSwitch
and create new objects based on that, but is there a better way? thanks解决方案The only way to do this would be to add an interface that also specifies the parameters you want to set:
public interface ISettable { string ID { get; set; } string Val { get; set; } } public void LoadData<T>(string id, string value) where T : ISettable, new() { this.Item.Add(new T { ID = id, Val = value }); }
Unfortunately I can't test to verify at the moment.
这篇关于创建参数类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!