返回 T 的对象实例的通用方法
我有相同的类,但在不同的命名空间中。例如:x.InHeaderType、y.InHeaderType 等...
我必须经常使用相同的参数创建这些类的实例。
这是一个示例:
x.InHeaderType inHeader = new x.InHeaderType();
inHeader.CompanyId = "TEST";
inHeader.UserId = "TEST";
inHeader.Password = "TEST";
inHeader.MessageId = " ";
是否可以创建如下方法:
public static T GetInHeaderProperty<T>()
{
T value;
// fill the properties of object and return the instance of T
// I will call it when I need x.InHeaderType or y.InHeaderType
}
提前致谢,
I have same classes but in different namespaces. ex: x.InHeaderType, y.InHeaderType etc...
I have to create instances of these classes with same parameters frequently.
Here is a sample:
x.InHeaderType inHeader = new x.InHeaderType();
inHeader.CompanyId = "TEST";
inHeader.UserId = "TEST";
inHeader.Password = "TEST";
inHeader.MessageId = " ";
Is it possible to create a method like:
public static T GetInHeaderProperty<T>()
{
T value;
// fill the properties of object and return the instance of T
// I will call it when I need x.InHeaderType or y.InHeaderType
}
Thanks in advance,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用以下代码:
这是 Tomas Jansson 答案的简化版本。它假设所有类型都有一个默认构造函数。
你可以这样称呼它:
You can use the following code:
This is a simplified version of Tomas Jansson's answer. It assumes that all the types have a default constructor.
You can call it like this:
首先,为什么两个不同的命名空间中有相同的类?
我会创建某种神奇的功能,例如:
这可能有用,但我不确定我会推荐它。您的代码可能存在其他类型的问题,迫使您执行此类操作,您应该首先修复这些问题。
更新:我假设你不能让对象继承相同的接口。如果可以的话你绝对不应该使用上面的代码,如果可以的话你应该使用下面的代码:
First of, why do you have the same class in two differente namespaces?
I would create somekind of magic function like:
That might work, but I'm not sure I would recommend it. You might have some other kind of issue with your code forcing you to do things like this that you should fix first.
UPDATE: I made the assumption that you can't make the objects inherit the same interface. If they can you should definitely not use the code above, if they can you should use the code below instead:
是的,您必须使用要设置的属性定义一个接口或基类,从中专门化您的特定类型,并使用泛型约束让编译器知道泛型类型参数具有这些属性。
详细信息:http://msdn.microsoft.com/en-us/library/ d5x73970.aspx
Yes, you'd have to define an interface or base class with the properties you want to set, specialize your specific types from that, and use generic constraints to let the compiler know that the generic type parameter has those properties.
More info: http://msdn.microsoft.com/en-us/library/d5x73970.aspx
这段代码有味道。拥有两种完全相同但位于不同命名空间中的类型并不是一个好主意。您可以将它们移至公共共享库吗?
我发现您正在使用服务参考。您需要每个端点的引用吗?您能否以某种方式重构您的引用以删除此重复项?
This code smells. Having 2 types exactly the same but in different namespaces isn't a great idea. Can you move them to a common shared lib?
I see you're using service references. Do you need to have references to each endpoint? Could you somehow refactor your references to remove this duplication?
我认为你需要:
I think you need: