小编Col*_*son的帖子

在处理方法中删除委托成员时,可以使用equals赋值吗?

我班上有以下代码

public class Receiver : IReceiver
{

    public event EventHandler Received;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (Received != null)
            {
                foreach (EventHandler delegateMember in Received.GetInvocationList())
                {
                    Received -= delegateMember;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码的作用是,当我处理我的类时,任何连接到Received事件的事件都将被单独删除.

如果下面的简洁版本具有相同的效果,我一直想知道是否而不是如此冗长

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            Received = null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

基本上,这归结为Microsoft在实现委托重载时如何创建运算符重载.我知道所有文档都说使用+ =来订阅,而= =取消订阅事件.我还看到该文档说当删除最后一个订阅者时,该事件将被指定为null.文档没有说的是将事件赋值为null,是否具有取消订阅所有事件的效果?

我很想知道这是否可行,如果有任何文档说明可能的简洁代码是正确的行为.

更新:

我一直在用c#编译器进行更多的挖掘,并发现null的赋值只能在定义事件的类中工作.+ =和 - =始终可以从课程内外获得.这使我认为使用= null版本是可以接受的.但是,这是猜测,我仍然没有看到任何明确说明这是支持功能的文档.

c# delegates dispose operators variable-assignment

7
推荐指数
1
解决办法
267
查看次数

来自类库的 Application.GetResourceStream

我正在尝试从类库加载资源。事实上,这并不完全正确。我正在尝试实现一种从代码中任何引用的项目加载资源的好方法。

为此,我正在开发一个 ResourceHelper 类。到目前为止就到此为止了。

public class ResourceHelper : IResourceHelper
{
    public string ReadTextFileFromResource(string resourceFileName)
    {
        StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(resourceFileName, UriKind.Relative));
        StreamReader streamReader = new StreamReader(streamResourceInfo.Stream);
        return streamReader.ReadToEnd();
    }
}
Run Code Online (Sandbox Code Playgroud)

当资源位于主应用程序项目中时,此代码非常有效。但是,如果我想拥有从主应用程序引用的类库中的资源,则找不到该资源。

这是我如何调用上述类的典型示例。

string sqlCommandText = _resourceHelper.ReadTextFileFromResource("Resources\\InternalSqlScripts\\DatabasePatchingTablesPreparation\\SelectPatchingTableNames.sql");
Run Code Online (Sandbox Code Playgroud)

有没有办法使这个引用成为正确的类库?我尝试过 pack:// uri,但是我只能让它抛出异常。

c# resources

6
推荐指数
0
解决办法
363
查看次数