Skip to main content
 首页 » 编程设计

c#之方法接口(interface)参数作为引用问题

2024年02月23日14TianFang

如果有人有更好的标题,请告诉我。

我做了一个 DisposeHelper 而不是这个:

private Something _thing; 
 
void Dispose() 
{ 
    if(_thing != null) 
    { 
        _thing.Dispose(); 
        _thing = null; 
    } 
} 

...我可以这样做:

private Something _thing; 
 
void Dispose() 
{ 
    DiposeHelper.Dipose(ref _thing); 
} 

但显然我无法将 IDisposable 提供给 DisposeHelper.Dispose 作为引用,除非我将 Something 转换为 IDisposable,如下所示:

private Something _thing; 
 
void Dispose() 
{ 
    IDisposable d = _thing; 
    DiposeHelper.Dipose(ref d); 
} 

...这意味着它不会使原始字段无效。

这是一个更抽象的例子。 DoThis 有效,DoThat 无效:

public class Test 
{ 
    public Test() 
    { 
        Something o = new Something(); 
 
        DoThis(o); 
 
        DoThat(ref o); 
    } 
 
    private void DoThis(IFoo obj) { } 
 
    private void DoThat(ref IFoo obj) { } 
} 
 
public class Something : IFoo { } 
 
public interface IFoo { } 

为什么我做不到?

请您参考如下方法:

我不知道您为什么不能这样做的技术原因。

然而,这有效:

var o = new Something(); 
DoThat(ref o); 
 
private void DoThat<T>(ref T obj) where T : class, IFoo {  
    obj = null; 
}