开发者

Extension Method irregular behavior

Consider the following:

public st开发者_开发百科atic class FileSerializer
{
    public static void SaveToFile<T>(this T obj, String fileName)
    {
        String dbFile = Path.Combine(Application.StartupPath, fileName);

        using (Stream stream = File.Open(dbFile, FileMode.Create))
        {
            BinaryFormatter bFormatter = new BinaryFormatter();
            lock (obj) bFormatter.Serialize(stream, obj);
        }
    }

    public static void LoadFromFile<T>(this T obj, String fileName, Boolean ensureExists)
    {
        String dbFile = Path.Combine(Application.StartupPath, fileName);

        if (!File.Exists(dbFile))
            if (ensureExists)
                throw new FileNotFoundException("File not Found!");
            else return;

        using (Stream stream = File.Open(dbFile, FileMode.Open))
        {
            if (stream.Length > 0)
            {
                BinaryFormatter bFormatter = new BinaryFormatter();
                obj = (T)bFormatter.Deserialize(stream);
            }
        }
    }
}

Even though I attach the debugger, and obj in the last line of the above code, has records, when I use the method as such:

lstServers.LoadFromFile("Servers.dat", false);

lstServers is ALWAYS empty.

Any ideas why?


You're essentially trying to change the reference of obj which can't be done in this way. The best you're going to get is a non-extension version of it:

public static T LoadFromFile<T>(String fileName, Boolean ensureExists)
{
    String dbFile = Path.Combine(Application.StartupPath, fileName);

    if (!File.Exists(dbFile))
        if (ensureExists)
            throw new FileNotFoundException("File not Found!");
        else return default(T);

    using (Stream stream = File.Open(dbFile, FileMode.Open))
    {
        if (stream.Length > 0)
        {
            BinaryFormatter bFormatter = new BinaryFormatter();
            return (T)bFormatter.Deserialize(stream);
        }
    }
}


LoadFromFile should not be an extension method, just a normal static method that returns its result:

lstServers = FileSerializer.LoadFromFile("Servers.dat", false);

The problem is that you assign to the instance parameter, and that doesn't have any effect on the variable passed to that parameter outside the method. You can't have by reference (ref or out) in an instance parameter in an extension method, which is what you would need to make your code work.


I had done this in this ugly way:

public static T LoadFromFile<T>(this String fileName, Boolean ensureExists);

so you can call it

MyType myObject = filename.LoadFromFile<MyType>(true);

But the biggest drawback is that this extension function will now be offered for every string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜