如何调用具有Type属性的泛型方法
本文关键字:Type 属性 泛型方法 何调用 调用 | 更新日期: 2023-09-27 18:27:55
我有以下情况:
public class ListingAttribute : AgencyServicesApi.Attribute
{
public Type ClrType { get; set; }
//public void SetValue(object value)
//{
// this.SetValueGen<ClrType>((ClrType)value);
//}
public void SetValueGen<TValue>(TValue value)
{
var t = typeof(TValue);
Value = // Use conversion methods based on ClrType here.
}
}
我不能将ListingAttribute
设为泛型,并为ClrType
使用泛型参数T
,因为我必须在运行时设置类型。AgencyServicesApi.Attribute
具有类型为string
的臭Value
属性,而不管Value
的内容是否应该是任何其他类型。我正在尝试扩展AgencyServicesApi.Attribute
,并基于配置文件,正确设置ClrType
,并能够添加适当的验证和ToString
实现。
如何调用泛型方法SetValueGen
并将ClrType
的类型作为类型参数传递给它?SetValue
被注释掉了,因为它没有编译,我也不希望它编译,但我一直在处理这个问题。
几乎按原样使用代码:
public class ListingAttribute : AgencyServicesApi.Attribute
{
public Type ClrType { get; set; }
public void SetValue(object value)
{
SetValueGen((dynamic)value);
}
public void SetValueGen<TValue>(TValue value)
{
var t = typeof(TValue);
Value = // Use conversion methods based on ClrType here.
}
}
但这似乎是错误的。。。你为什么不简单地做:
public void SetValue(object value)
{
var t = value.GetType();
Value = // Use conversion methods based on t here.
}