小编Rom*_*ner的帖子

我可以仅将自定义属性限制为void方法吗?

我有一个自定义属性,我想限制为返回类型为void的方法.

我知道我可以限制使用方法,[AttributeUsage(AttributeTargets.Method)]但似乎没有办法限制返回类型或方法签名的任何其他方面.

[System.Diagnostics.Conditional]属性完全具有我想要的限制.将其添加到非void方法会导致编译器错误:

Conditional属性在'(SomeMethod)'上无效,因为它的返回类型不是void

和IntelliSense说:

属性'System.Diagnostics.ConditionalAttribute'仅对具有'void'返回类型的属性类或方法有效.

如果我F12到了,ConditionalAttribute我看到它装饰有以下属性:

[Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = true)]
[ComVisible(true)]

其中没有任何关于返回类型的说明.

如何为Conditional属性完成,我可以为自定义属性执行相同的操作吗?

c# attributes postsharp custom-attributes

9
推荐指数
1
解决办法
580
查看次数

是否可以手动标记/取消标记对象以进行垃圾回收?

大多数资源声明垃圾收集器根据引用自行计算出来并且我不应该弄乱它.

我想知道我是否可以明确地告诉垃圾收集器它可以在保持引用的同时处理对象.

我想要做的是告诉垃圾收集器我目前不再需要一个对象(但可能会再次)然后在以后(如果)我再次需要该对象时我想检查它是否有已被处置.如果它我只是重新创建它,如果它没有我想从垃圾收集"取消标记"它直到我再次完成它.

这可能吗?

我计划实现类似于Lazy<T>类的东西.伪代码:

obj = new DisposeIfNecessary<LargeObject>(() => InitLargeObject());
obj.DoSomething(); // Initializes obj using InitLargeObject()
obj.DisposeIfNecessary(); // This is where the magic happens

... // obj might get disposed at some point

obj.DoAnotherThing(); // Might or might not call InitLargeObject() again
obj.Dispose(); // I will not need it again
Run Code Online (Sandbox Code Playgroud)

c# garbage-collection weak-references

4
推荐指数
1
解决办法
1853
查看次数

通过&lt;tab&gt;接收焦点时修改按钮样式,但单击时不修改

我想做的事

在用户界面上切换时,大多数WPF控件在接收到键盘焦点时会显示一个虚线边框。用鼠标单击它们时,它们不会显示此边框。

我有一个带有自定义控件模板的按钮,并且我希望具有与上述相同的行为,但是我不仅要添加边框,还想修改按钮本身的外观。

我尝试了什么

  • 自定义FocusVisualStyle。这没有给我足够的灵活性,因为由设置的模板FocusVisualStyle添加到按钮的顶部。据我所知,这不能用于以任何方式修改(样式,动画,...)按钮本身。

  • 使用带有IsFocused和/或IsKeyboardFocused属性的触发器以及带有Got/LostFocus和/或Got/LostKeyboardFocus事件的EventTriggers 对按钮进行样式设置。这也不起作用,因为当我也单击按钮时,所有这些似乎都被触发了。

范例程式码

<StackPanel VerticalAlignment="Center" Width="150">

    <StackPanel.Resources>

        <ControlTemplate x:Key="CustomButtonTemplate" TargetType="Button">
            <!--A simple black border with a content presenter-->
            <Border BorderBrush="Black" BorderThickness="1" CornerRadius="2">
                <ContentPresenter x:Name="Presenter" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2" />
            </Border>
            <ControlTemplate.Triggers>
                <!--When receiving keyboard focus modify the button text-->
                <Trigger Property="IsKeyboardFocused" Value="True">
                    <Setter TargetName="Presenter" Property="Content" Value="I have keyboard focus" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

        <Style x:Key="CustomFocusVisualStyle" TargetType="Control">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate> …
Run Code Online (Sandbox Code Playgroud)

.net c# wpf xaml controltemplate

3
推荐指数
1
解决办法
1184
查看次数