如何调用具有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被注释掉了,因为它没有编译,我也不希望它编译,但我一直在处理这个问题。

如何调用具有Type属性的泛型方法

几乎按原样使用代码:

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.
}