【问题标题】:How do I call a generic method with a Type property?如何使用 Type 属性调用泛型方法?
【发布时间】:2014-10-24 21:59:08
【问题描述】:

我有以下情况:

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 被注释掉了,因为它不能编译,我不希望它编译,但我被这件事困住了。

【问题讨论】:

    标签: c# .net generics


    【解决方案1】:

    几乎按原样使用您的代码:

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

    【讨论】:

    • 我想根据对象的ClrType 做出决定,而不是像您的第二个示例那样传递给SetValue 的值的类型。我只想接受与 ClrType 匹配的类型,但也许我必须只使用老式的类型验证检查。
    • 我明白了......我想反射是你最好的选择:if (ClrType.IsInstanceOfType(value)),但我仍然不清楚你到底想在这里做什么,所以我无法编辑我的答案有意义的方式,除非您提供更多详细信息
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    相关资源
    最近更新 更多