c# - Using Generics to Multiply Integers -
i have class called genericitem (first time using generics), suppose wanted multiply 2 items if of type integer, can see trying in method returncountermultiply
, not allow me multiply them although trying convert them , checking if of type integer.
namespace components { public class genericitem<t> { private t data; private t counter; public t data { { return data; } set { data = value; } } public genericitem(){} public genericitem(t _data) { data = _data; } public t returncountermultiply(t value) { int c = 0; int d = 0; if (counter.gettype() == typeof(int) && value.gettype() == typeof(int)) { //cant multiply 2 of type t, why if converting int?. return (t)convert.changetype(counter, typeof(int32)) * (t)convert.changetype(value, typeof(int32)); } return value; } } }
i appreciate explanation on this first time working on (this sample class understanding generics intro , generics classes, still having trouble understanding it.
you can this:
public class genericitem<t> { private t data; public t data { { return data; } set { data = value; } } public genericitem(){} public genericitem(t _data) { data = _data; } private dictionary<type, delegate> operations = new dictionary<type, delegate>() { { typeof(int), (func<int, int, int>)((x, y) => x * y) }, { typeof(string), (func<string, string, string>)((x, y) => x + " " + y) }, }; public t returncountermultiply(t value) { if (operations.containskey(typeof(t))) { var operation = (func<t, t, t>)(operations[typeof(t)]); return operation(data, value); } return value; } }
you need define, in dictionary, 1 operation per valid types you're going want use , works without converting of types (except cast func
).
i had these test results:
var gii = new genericitem<int>(42); var xi = gii.returncountermultiply(2); // xi == 84 var gis = new genericitem<string>("foo"); var xs = gis.returncountermultiply("bar"); // xs == "foo bar"
Comments
Post a Comment