简体   繁体   English

如何解析对象发送者

[英]how to parse for object sender

I have this method and I have no idea what object sender is sending 我有这种方法,我不知道对象发送者发送了什么

void xTreve(object sender, Microsoft.SilverlightMediaFramework.Core.CustomEventArgs<Microsoft.SilverlightMediaFramework.Core.Media.PlaylistItem> e)
{
}

how do I check to see what object sender contains 如何查看对象发件人包含的内容

I'm going to take it that your question is geared toward determining what sort of type sender is so you can work with it. 我要认为你的问题是为了确定什么类型的sender ,以便你可以使用它。

With that in mind, you would first need to get the type of sender , then you can cast it appropriately so you can operate on it. 考虑到这一点,您首先需要获取sender的类型,然后您可以适当地投射它,以便您可以对其进行操作。

For example, you can do the following in your method: 例如,您可以在方法中执行以下操作:

if (sender is TypeA)
{
    var iAmA = (TypeA)sender;

    // do something A-ish with sender
}
else if (sender is TypeB)
{
    var iAmB = (TypeB)sender;

    // do something B-ish with sender
}
else
{
    // do something else
}

Alternatively, the following does the same as the preceding: 或者,以下内容与前面相同:

Type type = sender.GetType();

if (type == typeof(TypeA))
{
    var iAmA = (TypeA)sender;

    // do something A-ish with sender
}
else if (type == typeof(TypeB))
{
    var iAmB = (TypeB)sender;

    // do something B-ish with sender
}
else
{
    // do something else
}

If the object is always going to be of the same type, but you just aren't sure what that type will be, then set a breakpoint inside the function and use the visual studio quickwatch window to inspect it. 如果对象总是属于同一类型,但您只是不确定该类型是什么,那么在函数内部设置断点并使用visual studio quickwatch窗口进行检查。 You will be able to see the control name and other properties of the sender object, as well as it's type. 您将能够看到发送方对象的控件名称和其他属性,以及它的类型。 Once you know the type you know what to cast sender as in the code if you need to manipulate it. 一旦你知道了类型,你知道如何在需要操作的情况下将代码转换为代码。

If you need to tell which instance sender is it depends if sender has some kind of property to identify it. 如果您需要告诉哪个实例发件人,它取决于发件人是否具有某种属性来识别它。 Consider the following code: 请考虑以下代码:

 public void randtest()
 {
     var rand = new Random();
     var obj1 = new object();
     var obj2 = new object();

     if (rand.Next() % 2 == 1)
     {
         method(obj1);
     }
     else
     {
         method(obj2);
     }

 }

public void method(object thing)
{
    //here i have no way to tell if thing is obj1 or obj2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM