5

ある PC から別の PC に BusinessObjects を転送したいと考えています。さまざまなオブジェクトの多くのコントラクトの使用を転送するために約 40 の異なるオブジェクト タイプについて考えてみると、常に同じタスク「オブジェクト A をコンピューター B に送信し、オブジェクトを DB に保存する」(すべてのオブジェクトには永続メソッドがあります)。

オブジェクトはさまざまなタイプを持つことができるため、ジェネリック メソッドを使用して次のことを行いたいだけです。

  1. BO オブジェクトをシリアライズする
  2. 別のPCに転送する
  3. 正しい型でデシリアライズする
  4. 整合性チェックを行う
  5. データベースに保存
  6. 私の問題です。

現時点では、タイプを eytra 情報として送信することを考えています。次に、次のようなことをしたい:

BinaryFormatter aFormatter = new BinaryFormatter();
aFormatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
Object.ParseTypeFromString(aObjektType) aObject = aFormatter.Deserialize(stream) as Object.ParseTypeFromString(aObjektType);

その後、ベースオブジェクトからジェネリックメソッドを使用してオブジェクトをデータベースに保存し、転送クラスをできるだけシンプルに保ちます。

このようなことをする可能性はありますか?または、私は完全に間違った方向に進んでいますか?別のアプローチでこのタスクを達成する方が簡単でしょうか?

4

1 に答える 1

5

If you don't know the type in advance, you cannot currently be doing anything in the C# that depends on the type. BinaryFormatter will already be deserializing it with the correct object type, but you code can usually just refer to the object as.... object:

object aObject = aFormatter.Deserialize(stream);

At this point, there are various options available to you:

  • use a common interface / base-class
  • use dynamic (interesting uses of dynamic include calling the most appropriate overload of a method, and switching into a generic method)
  • test the type explicitly with is, as or GetType(), for special-casing

As an example of the middle option:

object aObject = aFormatter.Deserialize(stream);
GenericMagic((dynamic)aObject);
OverloadMagic((dynamic)aObject);

...

void GenericMagic<T>(T obj) // possibly some constraints here too
{
    T x = ... // now we *have* the type, but as `T`;
              // of course, you still can't do many exciting
              // things unless you add constraints
}

// the correct one of these will be chosen at runtime...
void OverloadMagic(Customer cust) {...}
void OverloadMagic(User user) {...}
void OverloadMagic(Order order) {...}

Frankly, if I've had to deserialize (etc) something unknown I usually prefer to stay non-generic, just using object, GetType(), and maybe some reflection - it is still generic, even if it doesn't use generics.

于 2012-10-09T07:11:13.647 に答える