gpt4 book ai didi

c# - 我希望能够在内部派生自一个类,但不允许其他程序集中的类派生自该类

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:34 24 4
gpt4 key购买 nike

你好

我有以下设置:

程序集 1

public abstract class XX<T> : XX where T: YY { }
public abstract class XX {}

程序集 2

public class ZZ : YY {}
public class ZZFriend : XX<ZZ> {}

我在 YY 的时候在反射中使用了这个特性:

public class YY {
public Type FindFriend {
return GetType().Assembly.GetTypes().FirstOrDefault(
t => t.BaseType != null &&
t.BaseType.IsGenericType &&
typeof(XX).IsAssignableFrom(t) &&
t.BaseType.GetGenericArguments().FirstOrDefault() == GetType());
}
}

我想禁止非通用类 XX 的继承,例如:

public class ZZFriend: XX {}

或者,我需要一个类似的方法(可以在 YY.FindFrind() 的反射中使用):

public Type F(Type t) {
return GetTypeThatIsGeneric(XX, Type genericTypeParameter);
}

可以在 YY 中用作:

Typeof(XX<ZZ) == F(typeof(GetType())

希望这是有道理的...

提前致谢

索伦·罗克达尔

最佳答案

你可以在XX中创建一个内部构造器:

public abstract class XX
{
internal XX()
{
}
}

(或者,如果您已经有显式声明的构造函数,请将它们全部设为私有(private)或内部。)

这将阻止任何其他程序集声明派生类,因为没有可链接到的构造函数。

关于c# - 我希望能够在内部派生自一个类,但不允许其他程序集中的类派生自该类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24056342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com