是否可以在C#中定义部分泛型类

时间:2022-03-28 20:56:23

There is a class definition like the sample below:

有一个类定义,如下面的示例:

public abstract partial class MyClass<T> where T : MyClass<T>
{
....
}

And the second file consists of the definition below:

第二个文件包含以下定义:

partial class MyClass<T>
{
}

Also, I defined the partial part in the second file like the following code snippet and it was not conclusive:

此外,我在第二个文件中定义了部分部分,如下面的代码片段,它不是决定性的:

partial class MyClass<T> where T : MyClass<T>

The attempt to split this particular abstract class into two separate files by using partial keyword failed in C#. So, surprisingly the compiler intercepted it by generating compile errors. In fact a variable and property moved from the first partial into the second one and the compiler gave an error in the first class that the variable and property cannot be found.

在C#中使用partial关键字将此特定抽象类拆分为两个单独文件的尝试失败。因此,令人惊讶的是,编译器通过生成编译错误来拦截它。实际上,变量和属性从第一个部分移动到第二个部分,并且编译器在第一个类中给出了无法找到变量和属性的错误。

I tried many cases but no luck.

我试了很多但没有运气。

Is there something that we're doing wrong in splitting such a definition or that's how the compiler behaves?

在分割这样的定义或者编译器的行为方式时,我们是否存在错误?

2 个解决方案

#1


3  

Here is how a partial generic class would look like.

以下是部分泛型类的外观。

public partial class MyClass<T> where T : MyClass<T>
{
    public void SomeMethod() { Console.WriteLine("some method"); }
}

public partial class MyClass<T> where T : MyClass<T>
{
    public void SomeOtherMethod() { Console.WriteLine("some other method"); }
}

#2


0  

partial is used only to split a class across multiple source files. The class definition itself must be the same.

partial仅用于跨多个源文件拆分类。类定义本身必须相同。

#1


3  

Here is how a partial generic class would look like.

以下是部分泛型类的外观。

public partial class MyClass<T> where T : MyClass<T>
{
    public void SomeMethod() { Console.WriteLine("some method"); }
}

public partial class MyClass<T> where T : MyClass<T>
{
    public void SomeOtherMethod() { Console.WriteLine("some other method"); }
}

#2


0  

partial is used only to split a class across multiple source files. The class definition itself must be the same.

partial仅用于跨多个源文件拆分类。类定义本身必须相同。

相关文章