.net - C# Delegate as object -
disclaimer: unit-test related info question not relevant - can skip "the problem" if you're not familiar this, helps set context.
i have class need unit-test. looks this:
public class numberparser { public static void checkbyterange(string str){...} [...] public static void checkfloatrange(string str){...} [...] }
i want use nunit parametrized unit-test test these methods. here's test method:
[testcasesource("checkrange_overflow_inputs")] public void checkrange_overflow(string value, action<string> method) { assert.throws<exception>(() => method(value)); }
the test uses testcasesourceattribute
specify field contains list of sets of arguments test method.
now, nunit expects field called checkrange_overflow_inputs
, of type object[]
, contains object[]
elements, each of contains values arguments test method.
the problem:
ideally, i'd write field this:
private static readonly object[] checkrange_overflow_inputs = new object[] { new object[]{byte.maxvalue, numberparser.checkbyterange }, [...] new object[]{float.maxvalue, numberparser.checkfloatrange }, [...] };
but compiler complains can't cast method group object.
that makes sense - numberparser.checkbyterange
ambiguous, e.g. overloaded.
but how can compiler allow me save (as object) the method called numberparser.checkbyterange
takes string
, returns void
?
what tried (and failed succeeded):
[...] new object[]{byte.maxvalue, (action<string>)numberparser.checkbyterange }, [...]
if method static
, attempt have worked. can't work as
(action<string>)numberparser.checkbyterange
when checkbyterange
instance (non-static
) method because haven't told instance (this
) use. either:
- make
checkbyterange
static
method - tell instance use, i.e.
(action<string>)someinstance.checkbyterange
with them static
, following compiles fine me:
private static readonly object[] checkrange_overflow_inputs = new object[] { new object[]{byte.maxvalue, (action<string>) numberparser.checkbyterange }, new object[]{float.maxvalue, (action<string>) numberparser.checkfloatrange }, };
Comments
Post a Comment