创建参数类型的对象 [英] Create object of parameter type

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

问题描述

哎。是否有可能让一个方法允许用户传入某个特定类型的参数并让该方法实例化一个新类型的对象?我想要做这样的事情:(我不知道泛型是否应该走,但给了它一个镜头)

 <$ 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 a Switch 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屋!

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