如何使用使用接口的扩展方法

发布于 2025-01-20 09:27:40 字数 598 浏览 6 评论 0原文

因此,我正在尝试将具有这样的身体进行静态类,称为Action Extensions,

public static class ActionExtensions {
        public static IContainer Add<TObjectType>(this IContainer container, TObjectType obj) {
            return container;
        }
}

并使用Interface Icontainer。 我还有一个名为“学生”的课程:

public class Student, IContainer {
        public IList<int> Grades{ get;set;}
}

现在我想做类似的事情:

var student = new Student();
student.Add(3); //adding grade 3 to list of student's grades

但是我不想为学生班定义一个添加方法。宁愿使用我的方法中的方法。 这甚至可能吗?

So i'm trying to make a static class called ActionExtensions which has a body like this:

public static class ActionExtensions {
        public static IContainer Add<TObjectType>(this IContainer container, TObjectType obj) {
            return container;
        }
}

and uses interface IContainer.
I also have a class called Student with list of grades:

public class Student, IContainer {
        public IList<int> Grades{ get;set;}
}

Now I want to do something like this:

var student = new Student();
student.Add(3); //adding grade 3 to list of student's grades

But i don't want to define an Add method to a Student class. Rather use my method from ActionExtensions.
Is this even possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一杯敬自由 2025-01-27 09:27:40

可能。您可以这样做:

public interface IContainer<T>
{
   IList<T> Values { get; }
}

public static class ContainerExtensions
{
    public static void Add<T>(this IContainer<T> container, T value) =>
       container.Values.Add(value);
}

public class Student : IContainer<int>
{
    public List<int> Grades { get; set; }
    IContainer<int>.Values => Grades;
}

您可以像这样使用它

var student = GetSomeStudent();
student.Add(3);

It is possible. You could do it like this:

public interface IContainer<T>
{
   IList<T> Values { get; }
}

public static class ContainerExtensions
{
    public static void Add<T>(this IContainer<T> container, T value) =>
       container.Values.Add(value);
}

public class Student : IContainer<int>
{
    public List<int> Grades { get; set; }
    IContainer<int>.Values => Grades;
}

You can than use it like this

var student = GetSomeStudent();
student.Add(3);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文