《无形》C#中的对象 [英] "Shapeless" objects in c#

查看:59
本文介绍了《无形》C#中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 wcf 接收对象,每个对象都不同,我希望不是为每个接收到的对象创建一个对象,以便我可以操作它,每次将每个接收到的对象传递/复制到一个无形的对象.有这种事吗?

I am receiving objects using wcf, each object is different and I would like to instead of creating an object for each received object so I can manipulate it, to pass/copy each received object to only one shapeless object each time. It there such a thing?

伪代码示例:

Shapeless_object = received_obj_A;
if (Shapeless_object.name = "I_dont_know") {
   Shapeless_object.count++;
}

Shapeless_object = received_obj_B;
if (Shapeless_object.name = "I_dont_know_too") {
   Shapeless_object.count--;
   Shapeless_object.age = 20;
}

received_obj_A 和 B 不同参数不同但传入单个对象.我希望我的问题尽可能清楚.

received_obj_A and B are different with different parameters but passed in a single object. I hope I made my question as clear as possible.

推荐答案

你提到了 WCF 的起源:通过 partial class 可以很容易地向 WCF 类型添加接口:只需声明公共接口 - 也许:

You mention WCF origins: it is easy to add interfaces to WCF types via partial class: just declare the common interface - perhaps:

interface ICommon {
    string name {get;}
    // ...
}

然后告诉编译器为每个 WCF 类型推断接口:

Then tell the compiler to infer the interface for each of your WCF types:

namespace TheWcfNamespace {
    partial class SomeWcfType : ICommon {}
    partial class AnotherWcfType : ICommon {}
    partial class WhateverWcfType : ICommon {}
}

只要 SomeWcfType 等所有拥有成员来实现接口,您现在就可以将所有 WCF 对象视为 ICommon.

As long as SomeWcfType etc all have the members to implement the interface, you can now treat all your WCF objects as ICommon.

或者,您可以通过 dynamic 在这里做您想做的事情 - 只需将 Shapeless_object 替换为 dynamic - 但是,这似乎是滥用意图.这里更经典的实现是接口:

Alternatively, you might be able to do what you want here via dynamic - just replace Shapeless_object with dynamic - however, that seems an abuse of the intent. A more classic implementation here would be interfaces:

if(obj is IDontKnow) {
   // TODO: access as an IDontKnow
}

if (obj is IDontKnowToo) {
    // TODO: access as an IDontKnowToo
}

您当然可以将其与上面提到的 partial class 方法结合起来.

You can of course combine this with the partial class approach mentioned above.

这篇关于《无形》C#中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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