C#,可以将扩展方法添加到C#中的用户定义类(不是基类)

0 c# c#-3.0

我有一个用户定义的类

public class Student
{
    int rollno;
    public getrollno()
    {
        return rollno;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要有扩展方法checkifRollnoIs1(),它将返回true或false.

我能做到吗?我该怎么办?

Ode*_*ded 5

这是一种写一种方法:

public static class StudentExtensions
{
  public static bool checkifRollnoIs1(this Student s)
  {
    return s.getrollno() == 1;
  }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下 - 扩展方法实际上并没有添加到类中,它们就是这样出现的(intellisense magic).