Member lookup over generic constraint in C#? -
i have simple code : (simplified)
class program { static void main(string[] args) { var s1 = new student(); var s2 = new student(); mygenericclass<student> mgc = new mygenericclass<student>(); mgc.eq(s1,s2); } } class mygenericclass<t> t : person { public void eq(t t1, t t2) { console.writeline(t1.equals(t2)); } } class person { public bool equals(person p) { return true; } } class student : person { public bool equals(student obj) { return true; } }
the invoked method person's
, here question :
the mygenericclass
initialized student
t student. there constraint there : where t : person
- means person should base class. ( , student accomplish this)
question :
1) reason behavior relates generics ?
2) if , why still person's method running , not student ? stopping dealing student ?
edit , saw in spec
if "this behavior" mean calls method on person
, no, normal oop.
in order code call "the correct" method depending on actual t
used, need make method virtual
in base class, , override
in descendants:
class person { public virtual bool equals(person p) { return true; } } class student : person { public override bool equals(person obj) { return true; } }
but observe else well, in order equals
in student
override 1 in person
, needs take person
parameter well.
note generics doesn't mean "figure out method call @ runtime", it's still compiler determines, @ compile-time, methods call, , can see when compiling generic class person
class, cannot determine potential usage of student
.
you can verify behavior simple linqpad program:
void main() { base o = new derived(); o.test1(); o.test2(); } public class base { public void test1() { debug.writeline("base.test1"); } public virtual void test2() { debug.writeline("base.test2"); } } public class derived : base { public void test1() { debug.writeline("derived.test1"); } public override void test2() { debug.writeline("derived.test2"); } }
output:
base.test1 derived.test2
as warning (which have in code well):
warning: 'userquery.derived.test1()' hides inherited member 'userquery.base.test1()'. use new keyword if hiding intended.
Comments
Post a Comment