C# Listbox—直接使用反射调用类方法的选定项
我有这样一个问题场景:- 1) 列表框中包含诸如Car、Scooter和Bike等值。要单击的按钮C# Listbox—直接使用反射调用类方法的选定项,c#,asp.net,C#,Asp.net,我有这样一个问题场景:- 1) 列表框中包含诸如Car、Scooter和Bike等值。要单击的按钮 <div> <asp:ListBox ID="lst" runat="server"> <asp:ListItem Text="Bike" Value="Bike"></asp:ListItem> <asp:ListItem Text="Car" Value="Car"></asp:ListItem>
<div>
<asp:ListBox ID="lst" runat="server">
<asp:ListItem Text="Bike" Value="Bike"></asp:ListItem>
<asp:ListItem Text="Car" Value="Car"></asp:ListItem>
<asp:ListItem Text="Scooter" Value="Scooter"></asp:ListItem>
</asp:ListBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Invoke" />
</div>
3) 现在,在按钮单击事件处理程序“Button1\u click”上,我想基于列表框中的选定值,仅使用反射调用getData()方法
请帮帮我
string data = (string)Type.GetType("MyAwesomeNamespace." + "Car").GetMethod("getData").Invoke(null, null);
Type.GetType
获取您的类型。您可能希望在名称空间中加上前缀GetMethod
获取getData方法Invoke
将执行该方法。由于该方法是静态的,因此使用null调用该方法将起作用。如果它不是静态的,则必须将null替换为该对象的实例。另外,第二个null用作参数,在本例中为none我不是在评判你,但是创建一个接口并在所有三个类上实现它们不是更好吗?我如何从方法中获取返回字符串。lbl1.Text=Type.GetType(sValue).GetMethod(“getData”).Invoke(null,null);。这句话不管用。我需要在这里投点什么吗?编辑我的答案以反映您的评论;)invoke方法不接受一个参数。这仍然给我错误:-受保护的无效按钮1_-Click(对象发送方,事件参数e){string sValue=lst.SelectedValue;lbl1.Text=(string)Type.GetType(sValue)。GetMethod(“getData”).invoke(null,null);}Type.GetType获取您的类型。您可能希望在名称空间中加上前缀。所以你不能把它放在“车”里。在名称空间前面加上前缀,所以如果Car位于“MySystem.Vehicles”中,Type.GetType(sValue)应该是Type.GetType(“MySystem.Vehicles.”+sValue)
string data = (string)Type.GetType("MyAwesomeNamespace." + "Car").GetMethod("getData").Invoke(null, null);