在泛型方法中调用重载方法 [英] calling an overloaded method in generic method
本文介绍了在泛型方法中调用重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Test
{
public BinaryWriter Content { get; private set; }
public Test Write<T> (T data)
{
Content.Write(data);
return this;
}
}
它不会编译.
1. The best overloaded method match for 'System.IO.BinaryWriter.Write(bool)' has some invalid arguments
2. Argument 1: cannot convert from 'T' to 'bool'
似乎Test.Write总是试图调用BinaryWriter.Write(bool).有什么建议吗?
it seems like Test.Write is always trying to call BinaryWriter.Write(bool). any suggestions?
推荐答案
重载解析发生在编译时,在这种情况下,关于T的消息一无所知,因此没有重载适用.
Overload resolution happens at compile-time, and in this case nothing is known about T, so no overload is applicable.
class Test
{
public BinaryWriter Content { get; private set; }
public Test Write<T>(T data)
{
Content.Write((dynamic)data);
return this;
}
}
但是,这当然可能会带来一些问题.例如,如果将DateTime发送到该方法,则appliction可以正常编译.但是,它将引发异常.
But of course it could make some problems. For example, appliction will compile fine, if you will send DateTime to the method. But, it will throw exception.
这篇关于在泛型方法中调用重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文