CodeGo.net>如何调用一个泛型约束的方法使用类型参数没有约束?
作者:互联网
假设我有一个方法:
public void ExampleMethod<T>(T x) where T : struct // or new()
{
// example usage, similar to what's actually happening
var z = (T)Enum.Parse(typeof(T), privateFieldOfTypeString);
// do something depending on values of x and z
// possibly using other methods that require them being enums
// or in case of the new() constraint:
// var t = new T() and do something together with x
}
我想按如下方式使用它:
public void CallerMethod<S>(S y)
{
if (typeof(S).IsEnum) // or some other invariant meaning that `S` is "new()able"
{
ExampleMethod(y); // won't compile
}
}
因此,在运行时我知道S满足ExampleMethod< T>的约束.我知道有可能使用反射来称呼它,类似于:
this
.GetType()
.GetMethod(nameof(ExampleMethod<object>))
.MakeGenericMethod(typeof(S))
.Invoke(this, new object[] { y });
没有反射有可能吗?
注意:这是来自真实示例的简化代码,显然我无法控制这些方法的签名,因此“将约束添加到CallerMethod”和“从示例方法删除约束”的答案无效.
是的,整个事情应该重新设计,这样整个问题就不会出现.但是,在现实生活中,“整个事情”常常太大,太耦合且太冒险而无法重写.一些要求已经以一种意想不到的方式发生了变化-因此出现了明显的代码气味,我试图通过将其隐藏在一个看起来很讨厌的地方来将其最小化.
解决方法:
您可以使用动态:
if (typeof(S).IsEnum)
{
ExampleMethod((dynamic)y);
}
标签:generic-constraints,generics,c 来源: https://codeday.me/bug/20191108/2007690.html