简体   繁体   中英

Overloading generic Method with different parameters to reduce redundancy

I am trying to get a better understanding of generics but I am stuck because I want to refactor my code example but it doesn't work and my understanding isn't good enough to see why and how I could fix it:

My example is just for education purpose, so I don't worry about performance or memory leaks etc...

public static void InstanceView<TView, TViewModel>() 
    where TView : Window
    where TViewModel : class, new()
{
    var viewToInstance = (TView) Activator.CreateInstance(typeof (TView), new TViewModel());
    viewToInstance.ShowDialog();
    viewToInstance.Close();
}

public static void InstanceView<TView>()
    where TView : Window
{
    var viewToInstance = (TView)Activator.CreateInstance(typeof(TView));
    viewToInstance.ShowDialog();
    viewToInstance.Close();
}

I don't want the redundancy

viewToInstance.ShowDialog();
viewToInstance.Close();

My workaround for the moment is:

private static void displayHandle<T>(T window) where T : Window
{
    window.ShowDialog();
    window.Close();
}

I call this in both InstanceView implementation instead of ShowDialog() etc.

I have tried something like:

public static void InstanceView<TView>()
where TView : Window
{
    InstanceView<TView, null>;
}

But it doesn't work. Is there a way to achieve this ?

PS: I am using Visual Studio 2010

Thank you in advance!

But it doesn't work. Is there a way to achieve this ?

null is not a type parameter. More specifically in C#, it isn't even a type. Since you have a constraint on TViewModel to be a reference type with a default constructor, you can pass an object type to it, or any other reference type that fits the constraints:

public static void InstanceView<TView>()
where TView : Window
{
    InstanceView<TView, object>;
}

This will also work:

public class Void { }

public static void InstanceView<TView>()
where TView : Window
{
    InstanceView<TView, Void>;
}

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