派生类的泛型参数中的“此”类型

本文关键字:类型 参数 泛型 派生 | 更新日期: 2023-09-27 18:36:12

有没有办法在类型参数中指定参数是对象实例的类型?

例如,为了说明,我有:

public abstract class Model
{
    public int Prop1 { get; set; }
}

对于我的例子,我想要一个方法,该方法将返回传入Model的属性(显然这是一个愚蠢的方法,但它明白了这一点)。我可以让它作为扩展方法工作:

public static class Extensions
{
    public static U Property<T, U>(this T model, Expression<Func<T, U>> property) where T : Model
    {
        return property.Compile().Invoke(model);
    }
}

这样我就可以拥有

public class DerivedModel : Model
{
    public string Prop2 { get; set; }
}

并做

var myString = new DerivedModel().Property(a => a.Prop2);

此方法似乎应该是 Model 类的一部分,如下所示:

public T Property<T>(Expression<Func<ThisDerivedInstanceOfModel, T>> property)
{
    return property.Compile().Invoke(this);
}

以便扩展方法对Property()的相同调用可以在Model的实例上执行。

我意识到这有点奇怪,可能根本不是 C# 的功能,并且解决方法扩展方法运行良好 - 但如果可能的话,我更愿意将其作为实例方法,因为对我来说似乎"更好"。

派生类的泛型参数中的“此”类型

有没有办法在类型参数中指定参数是对象实例的类型?

不。不好意思。有时我可以看到它很有用,但这不是你能做到的。在过去的:(中,我遇到了类似的问题