繁体   English   中英

在方法的中途添加泛型类型约束

[英]Adding a generic type constraint halfway through a method

我有两种通用方法 -

public CustomObject<T> MethodA<T>(T arg1) where T : class
{
    ...
    return MethodB<T>(arg1);
}


public CustomObject<R> MethodB<R>(R arg2) where R : class, IInterface
{
    ...
    return new CustomObject<R>();
}

这个问题显然是我不能调用MethodB与不实现类型IInterface (其中T不)。 但是,如果我这样做了 -

public CustomObject<T> MethodA(T arg1) where T : class
{
    ...
    var casted = arg1 as IInterface;
    if (casted != null)
    {
        return MethodB<T>(casted);
    }
}

显然这不会编译,但它应该,不是吗? 我怎样才能让编译器知道,我知道, casted农具IInterface ,是一类,因此调用MethodB是好的? 这里的大皱纹可能是我正在尝试返回CustomObject<T>

你需要使用反射来完成这项工作。

尝试这个:

public CustomObject<T> MethodA<T>(T arg1) where T : class
{
    if (arg1 is IInterface)
    {
        var method = this.GetType().GetMethod("MethodB").MakeGenericMethod(arg1.GetType());
        return (CustomObject<T>)method.Invoke(this, new [] { arg1 });
    }
    return null;
}

因为您的CustomObject<T>是通用的,所以它有问题。 例如, CustomObject<object>CustomObject<string>不可互换,但您可以在两者之间进行转换。

你可以这样做一个解决方法:

public class CustomObject<T> where T : class {}
public interface IInterface { }

public static class CustomObjectConverter
{
    public static CustomObject<T1> ConvertTo<T1, T2>(CustomObject<T2> other)
        where T1 : class
        where T2 : class
    {
        return new CustomObject<T1>();
    }
}

public CustomObject<T> MethodA<T>(T arg1) where T : class
{
    if (arg1 is IInterface inf)
    {
        var b = MethodB(inf);
        return CustomObjectConverter.ConvertTo<T,IInterface>(b);
    }
    return null;
}
public CustomObject<T> MethodB<T>(T arg2) where T : class, IInterface
{
    return new CustomObject<T>();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM