简体   繁体   中英

Difference between generic function and function with Type parameter

I just wondered what is the difference between using a function that takes a parameter of type Type (and some more parameter) and a generic function that just wants the type in angle bracket ?

Idea behinde: I want to write a function that saves a type on ma filesystem as XML file. Since the XmlSerializer needs to have the type of object to serialize, I want to know: What is better?

private bool SerializeIt(object o, Type t, string filePath)
{
    bool result = false;
    try
    {
        if (File.Exists(filePath))
            File.Delete(filePath);

        XmlSerializer serializer = new XmlSerializer(t);
        using (FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write))
        {
            serializer.Serialize(fs, o);
        }
        result = true;
    }
    catch (Exception ex)
    {
        result = false;
        Debug.WriteLine(ex);
    }

    return result;
}

private bool SerializeIt<T>(T o, string filePath)
{
    bool result = false;
    try
    {
        if (File.Exists(filePath))
            File.Delete(filePath);

        XmlSerializer serializer = new XmlSerializer(o.GetType());
        using (FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write))
        {
            serializer.Serialize(fs, o);
        }
    }
    catch (Exception ex)
    {
        result = false;
        Debug.WriteLine(ex);
    }

    return result;
}

Your first method will only work with the type SomeData1 , since that is the type you specify. The other method works with any type passed through T .

You could solve the above issue with o.GetType() instead of typeof(SomeData1) . Still, the second method gives you the opportunity to use a base class as serialization base, which will clear out all properties in the deriving class.

Function private bool SerializeIt(object o, Type t, string filePath) is evaluated at runtime. Where function private bool SerializeIt<T>(T o, string filePath is evaluated at compile time. That is inserting the specified type in IL code.

There is a lot of differencies. Firstly you can create constraints for generic parameters, eg:

private bool SerializeIt<T>(T o, string filePath) where T: ISomething

Secondly - free type inference for generic types.

private bool SerializeIt<T>(T o, string filePath)

Something something = new Something();
o.SerializeIt(something, ""); // dont need to pass type (can infer from first argument).

Thirdly - you work on concrete strong type, eg:

private bool SerializeIt<T>(T o, string filePath)

Generally it makes interface simpler and cleaner. You dont have to use loosely typed objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM