我正在开发一个ASP.NET Web表单项目,我已经创建了一个自定义事件处理程序。
potected void MyEventHandler(object sender, EventArgs e)
{
var actualObject = (ActualObject) sender;
// I don't want to do what is in the line above. I want to use my EventArgs
// parameter 'e' which contains a property of type Type to cast the sender
// object into the underlying type defined in the EventArg property.
// I want to do something like this ...
var actuaObject = (typeof(e.TypeProperty)) sender;
//i.e. I don't want to explicitly reference the type to which
//I'm trying to cast between the parentheses
}
希望这个问题不会太复杂。
答案 0 :(得分:0)
您可以在TypeConverter
类
dynamic
功能
TypeConverter converter = new TypeConverter();
dynamic variable = converter.ConvertTo(sender, typeof(e.TypeProperty));
然后你可以访问你的属性,但你不能使用IntelliSense
,这是一个缺点。除此之外,它应该可以正常工作。
答案 1 :(得分:0)
您可以将Convert.ChangeType
方法用于标准类型;但是,它不会转换自定义类型。
public static Object ChangeType(
Object value,
Type conversionType
)
示例:
object d = Convert.ChangeType("3.1416", typeof(double));
请注意,返回的值的类型为object
。因此,您可能仍需要在某处进行演员表。