Cast vs Serialize/Deserialize C#

Geo*_*mes 1 c# serialization casting deserialization

Scenario

I have a virtual method in a base class, which takes an object as a parameter.

I override this in derived classes - more specifically, view models - in order to work with the different objects from there, also:

public override void SomeMethod(object parameter)
{
    // ...

    base.SomeMethod(parameter);
}
Run Code Online (Sandbox Code Playgroud)

EDIT: Just to clarify - I am unable to change the SomeMethod signature in the base class - unfortunately, I'm stuck with object as the type :(

Let's say that each derived class will expect a different type to the next, but I know about what type each class needs to use in order to pass it and consume it.

In particular, I will ask about Dictionary<string, string>; but I would be interested to see if this applies to other types.


Imagine this...

So, let's say I have a Dictionary<string, string> I want to pass to SomeMethod():

Here's the dictionary:

// create the dictionary
var myItem = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
    // ...
};
Run Code Online (Sandbox Code Playgroud)

What I have so far...

Possibilities...

我可以想到两种可能的方法来传递myItemSomeMethod()

// Pass the myItem directly as an object

SomeMethod(myItem);
Run Code Online (Sandbox Code Playgroud)

或者

// Serialize the myItem to a string, and then pass that as an object
// I'm using JsonConvert in this case

object parameter = JsonConvert.SerializeObject(myItem);
SomeMethod(parameter);
Run Code Online (Sandbox Code Playgroud)

消耗该物品

然后,我可以使用两种可能的方式来使用我刚刚传递给的项目SomeMethod(),具体取决于我上面分别使用的方法:

public override void SomeMethod(object parameter)
{
    // Cast the parameter back to a dictionary
    Dictionary<string, string> unboxedItem = parameter as Dictionary<string, string>;

    // consume away...
}
Run Code Online (Sandbox Code Playgroud)

或者

public override void SomeMethod(object parameter)
{
    // Deserialize the parameter from a string
    Dictionary<string, string> deserializedItem =
                    JsonConvert
                    .DeserializeObject<Dictionary<string, string>>(parameter as string);

    // consume away...
}
Run Code Online (Sandbox Code Playgroud)

帮助?

这 2 种方法中哪一种会占用更少的资源?

我听说装箱和拆箱最终可能会很慢(在大规模情况下)。

是的,我知道我实际上是在第二种方法中对序列化进行装箱string- 就资源而言,我装箱/拆箱的类型是否重要?

向对象进行投射/从对象进行投射会对性能产生影响吗?或者,反序列化会真正影响性能吗?

更新:所以,看来我有点愚蠢,并且误解了装箱/拆箱的东西 - 所以我更新了问题以反映这一点

非常感谢您的意见、建议和帮助:)

Sef*_*efe 5

首先,拳击不是这里发生的事情。装箱是指准备将值类型作为引用类型放入堆上的操作。如果您的字典是值类型,那么它确实需要装箱和拆箱。

唉,字典是一种引用类型。这意味着不会有拳击比赛。该引用将按原样传递给您的方法。你的方法要做的是向下转换为字典。虽然这需要评估对象的 RTTI(运行时类型信息),但通常不会注意到性能影响(极端情况除外)。

然而,您的序列化/反序列化解决方案要昂贵得多。您必须在堆上为字符串分配空间,必须序列化、反序列化,并且该字符串最终需要被垃圾收集。你可以预期,这比简单的沮丧要昂贵得多。

更新:

需要澄清的是,您仍然可以预期装箱比序列化更便宜。因此,即使对于值类型,也没有理由选择序列化。特别是因为您很有可能在整个序列化往返过程中至少进行一次装箱操作。