首页 \ 问答 \ 使用扩展类的静态属性扩展泛型接口[duplicate](Extending a generic interface with a static property of the extended class [duplicate])

使用扩展类的静态属性扩展泛型接口[duplicate](Extending a generic interface with a static property of the extended class [duplicate])

这个问题在这里已有答案:

我有一个通用的接口,我希望有一个self类型的属性

public interface IFoo<TBar> : where TBar : ISomething 
    {
        TBar Prop1 { get; set; }
        IFoo<TBar> Unset { get; }
    }

这是好的,直到我继承这个并创建一个(非泛型)类:

public class FooDesired : IFoo<Bar>
    {
        public Bar Prop1 { get; set; }
        public static Foo Unset { get { return new Foo(); } }
    }

public class FooReality : IFoo<Bar>
    {
        public Bar Prop1 { get; set; }
        public static IFoo<Bar> Unset { get { return new Foo(); } }
        public IFoo<Bar> IFoo<Bar>.Unset { get { return new Foo(); } }
    }

我目前的实现有两个问题:

1.此实现不实际允许Unset为静态。 我已经通过显式接口实现来解决这个问题,但我总是对“欺骗”系统持谨慎态度。

2.如果我调用Foo.Unset我总是要把它强制转换回Foo(除非我设置了一个隐式运算符,但这只是隐藏问题而不是解决它)。

编辑真实问题:如何在一组类中强制存在静态属性?

**编辑:**对于那些热衷于用例的人,让我们假设所有动物物种一旦完全成熟就会在其体内有一定数量的骨骼。 因此,我希望Animal在Cat,Dog和Human上强制执行静态NumBones属性。 这不包括原始类'类型的静态属性,但注释与答案有良好的链接。


This question already has an answer here:

I have a generic interface which I would like to have a property of type self i.e.

public interface IFoo<TBar> : where TBar : ISomething 
    {
        TBar Prop1 { get; set; }
        IFoo<TBar> Unset { get; }
    }

This is fine until I inherit this and create a (non-generic) class:

public class FooDesired : IFoo<Bar>
    {
        public Bar Prop1 { get; set; }
        public static Foo Unset { get { return new Foo(); } }
    }

public class FooReality : IFoo<Bar>
    {
        public Bar Prop1 { get; set; }
        public static IFoo<Bar> Unset { get { return new Foo(); } }
        public IFoo<Bar> IFoo<Bar>.Unset { get { return new Foo(); } }
    }

I have two issues with the current implementation of this:

1. This implementation does not actual allow Unset to be static. I've worked my way around that with Explicit Interface Implementation but I'm always wary of "tricking" the system.

2. If I call Foo.Unset I always have to cast it back to Foo (unless I setup an implicit operator but that's just hiding the issue rather than solving it).

Edited Real Question: How can I enforce the existence of a static property in a set of classes?

**Edit: ** For those who are keen for a use case, let's assume all Animal species have a set number of bones in their bodies once fully mature. Therefore I would like Animal to enforce a static NumBones property on Cat, Dog and Human. This doesn't cover the static property being of the original class' type but the comments have good links to answers to that.


原文:https://stackoverflow.com/questions/36691294
更新时间:2023-07-30 18:07

最满意答案

它更改了最里面的函数( _view ),因此它看起来与它包装的函数具有相同的名称,属性和文档。 这有助于在Python解释器中使用help() ,并使堆栈跟踪更清晰。

(注意:同样的事情基本上是由stdlib中包含的functools.wraps装饰器完成的。)


It changes the innermost function (_view) so it appears to have the same name, attributes, and documentation as the function it wraps. This aids when using help() in the Python interpreter, and makes stack traces more clear.

(Note: The same thing is basically done by the functools.wraps decorator included in the stdlib.)

相关问答

更多
  • 使用user_passes_test装饰器: from django.contrib.auth.decorators import user_passes_test @user_passes_test(lambda u: u.is_superuser) def my_view(request): ... Use the user_passes_test decorator: from django.contrib.auth.decorators import user_passes_test ...
  • 只需在您的测试用例setUp方法中使用超级用户登录即可 from django.test import TestCase from django.contrib.auth.models import User class TestThatNeedsLogin(TestCase): def setUp(self): User.objects.create_superuser( 'user1', 'user1@example.com', ...
  • 您需要使用method_decorator来装饰dispatch方法。 class SetUserData(View): @method_decorator(cls_method_staff_member_decorator) def dispatch(self, *args, **kwargs): return super(SetUserData, self).dispatch(*args, **kwargs) 这里解释一下 或者在urls装饰: urlpatterns ...
  • 您可以在第一次调用装饰器时设置会话变量,并检查此值以确定是否应该再次显示警报。 另一种方式可能是编写自己的中间件。 You could set a session variable when the decorator has been called for the first time and check for this value to determine if the alert should be shown again. Another way could be to write your ow ...
  • 您不需要在此行上显式传递对self的引用: val = self.__old_save(self, *args, **kwargs) 它是在对象引用上调用的方法。 以这种方式显式传递它会使它被视为save方法的其他参数之一,预期是一个字符串或数字。 You do not need to explicitly pass a reference to self on this line: val = self.__old_save(self, *args, **kwargs) It is a method ...
  • 它更改了最里面的函数( _view ),因此它看起来与它包装的函数具有相同的名称,属性和文档。 这有助于在Python解释器中使用help() ,并使堆栈跟踪更清晰。 (注意:同样的事情基本上是由stdlib中包含的functools.wraps装饰器完成的。) It changes the innermost function (_view) so it appears to have the same name, attributes, and documentation as the function ...
  • 装饰器没有什么神奇之处,它是一个函数,它将函数(或类)作为输入进行装饰,并对其进行一些更改。 如果我们查看login_required装饰器[GitHub] ,我们会看到: def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redir ...
  • from functools import wraps def friendship_checker(f): @wraps(f) def wrapped(request, *args, **kwargs): if hasattr(request.user, 'friend'): return f(request, *args, **kwargs) else: return HttpResponseRedirec ...
  • 如果要将参数传递给装饰器,则需要定义第三级嵌套; 第一级接受参数并返回第二级,它接受函数本身。 所以: def condition_or_redirect(condition, redirect_to): def wrapper(view_func): def wrapped(request, *args, **kwargs): if not condition(request.user): return HttpRespons ...
  • 因为如果测试成功,您实际上没有调用视图函数。 if 'isPrivateAlfaUser' not in request.session or request.session['isPrivateAlfaUser'] != True: return render_to_response('homepage.html') else: return func(request, *args, **kwargs) 作为辅助说明,此处不需要外层包装器,因为装饰器不带任何参数。 如果放弃它,你还需要 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。