Create object of parameter type

橙三吉。 提交于 2019-12-08 08:51:28

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.

If the ID and Val properties come from a common base class or interface, you can constrain T to inherit that type.

For example:

public void LoadData<T>(string id, string value) where T : IMyInterface, new()

You can then use all the members of IMyInterface on T 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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!