Can anybody help me with refactoring of such methods:
public static void MethodA(this SceneObject obj, double value)
public static void MethodA(this SceneObject obj, long value)
public static void MethodA(this SceneObject obj, int value)
public static void MethodB(this IEnumerable<MyData> sObjects, IEnumerable<int> values)
public static void MethodB(this IEnumerable<MyData> sObjects, IEnumerable<long> values)
How can I make them one generic method that can take any kind of param? Thanks.
Just use the generic feature.
public static void MethodA<T>(this SceneObject obj, T value)
Then you can use it like this:
SceneObject.MethodA<long>(50);
Sceneobject.MethodA<int>(50);
The value
parameter automatically gets the type of T. So in this case long
or ìnt
.
If your question just is about how to make your definition generic, it could be done like:
public static void Method<T>(this object, T value)
If you want to be able to use it on all kind of objects or not you may want to adjust the type you are extending.
The usage would then be:
someObject.Method<int>(1);
someObject.Method<long>(1);
someObject.Method<double>(1);
someObject.Method<List<int>>(new List<int> { 1, 2, 3 });
If you would like to have a numeric constraint you could also do something like:
public static void Method<T>(this object, T value) : where T : IComparable, IComparable<T>
public static void MethodA<T>(this SceneObject obj, T value) where T : struct
public static void MethodB<T>(this IEnumerable<MyData> sObjects, IEnumerable<T> values) where T : struct
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.