c# - Can I use Generics to get the property of a passed struct? -
i trying use generics pass in struct function , have function access properties. want utilize generics more because supposed "safe , efficient". here's code looks like.
class
class foo { struct { int a; int b } struct b { int a; int b; } }
generic function
void bar<t> (t input) { var = input.a; //this says know nothing }
function call
bar<foo.a> (aobj);
can generics used this?(that access object's data members...) or can create over-loaded method? parts of objects trying access function common both types, that's why thought use generics.
using generics not imply can use duck typing. c# statically typed language, need following:
first, define interface defines common interface of a
, b
:
interface ihasab { int { get; } int b { get; } }
then, have struct
s implement interface:
struct : ihasab { public a(int a, int b) { = a; b = b; } public int { get; } // note: `a` , `b` properties, not fields public int b { get; } // before; interfaces not allow declare fields. // note also: mutable structs bad idea! that's why implement // `a` , `b` read-only properties. } struct b : ihasab { … } // same `a`
now can implement method bar
additional generic type parameter constraint where t : ihasab
:
void bar<t> (t input) t : ihasab { var = input.a; }
the constraint on t
lets compiler know can expect t
be. knows t
type implements ihasab
, , therefore has 2 properties a
, b
(since interface consists of). that's why can access .a
on input
.
note don't need make bar
generic:
void bar(ihasab input) { var = input.a; }
in latter case, note input
reference-typed parameter. if passed 1 of a
or b
structs method, have boxed (i.e. turned value type reference type). there's overhead involved in that.
i won't go further dangers of mutable structs , boxing can happen in situations structs implement interfaces, since that's quite different matter altogether; recommend spend little time researching these topics. ;-)
Comments
Post a Comment