Can I check if an object is comparable to some other type?
I'd like to write some code like this:
if (obj.IsComparableTo(integer))
Console.Write("successed");
Is this possible? If not, is there an a开发者_StackOverflow中文版lternative way of determining this?
Depending on what you mean by comparable, maybe:
var comparable = obj as IComparable<int>;
if(comparable != null) Console.Write("successed");
However, this only accounts for the interface, which would be rare. Most implicit conversions will be harder to check for. If you add more context, maybe a more appropriate solution will be easier to spot.
You object has to implement the interface IComparable<int>
public class Foo : IComparable<int>
{
}
It is not possible to compare two different types of objects unless they implement the IComparable
interface.
i've found it :
public bool isComparable<t>(object o)
{
try
{
object r = (t)o;
}
catch
{
return false;
}
return true;
}
to use it:
if (isComparable<int>(32).ToString())
Console.WriteLine("success");
else
Console.WriteLine("fail");
精彩评论