I have a method that looks like below:

private void someEvent(RoutedEventArgs e)
{
    if(e.OriginalSource == typeof(a.b.c.somePages))
}

This method will be in my viewModel. From breakpoint, I can see there is this e.OriginalSource which has my xaml page somePages as value. Hence I'm trying to compare the value. But it's giving me warning as below:

Possible unintended reference comparison; to get a value comparison, 
cast the left hand side to type 'System.Type'

So I updated my code to if((System.Type)e.OriginalSource == typeof(a.b.c.somePages)) but the warning is still there. May I know what's wrong?

有帮助吗?

解决方案

In this situation, you need to type cast. You can not get the type of an object without a cast because for e.OriginalSource type will be Object. Besides, in the construction typeof is to be an object of System.Type type:

Used to obtain the System.Type object for a type.

Therefore try this:

Page page = e.OriginalSource as Page;

if (page != null) 
{
    string test = page.ToString();
}

Or just use ToString() method for e.OriginalSource like you mentioned.

其他提示

I'm not sure if it's the correct way but I able to compare using the following way:

if(e.OriginalSource.ToString() == "a.b.c.SomePages")

You were comparing an object to type. If you intended to compare type of the object instead, try to do it this way :

if (e.OriginalSource.GetType() == typeof(a.b.c.somePages))
{

}

Another way is using is operator :

if(e.OriginalSource is a.b.c.SomePages)
{

}

From MSDN link above, about is :

"Checks if an object is compatible with a given type".

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top