如何在不知道底层记录类型的情况下在接口上使用关键字“with”?

Ste*_*lis 11 c# interface c#-9.0 c#-record-type

在 C# 中,是否有一种方法可以with在不知道对象的类型(或基类型)的情况下在接口上使用关键字?

我正在想象类似DoSomething以下伪代码中的方法(这不是有效的 c#)。该代码DoSomething预计会对所有实现ISomeRecord.

DoSomething2方法可以编译,但仅适用于类型的记录SomeRecord,不适用于SomeRecord.

public interface ISomeRecord
{
  bool SomeProp { get; }
}

public record SomeRecord : ISomeRecord 
{ 
  public bool SomeProp { get; init; } 
}

public class SomeUtil
{
  public ISomeRecord DoSomething(ISomeRecord rec)
  {
    return ( rec as record ) with { SomeProp = false };
  }
  public ISomeRecord DoSomething2(ISomeRecord rec)
  {
    return ( rec as SomeRecord ) with { SomeProp = false };
  }
  public ISomeRecord DoSomething3<T>(T rec) where T : struct, ISomeRecord
  {
    return rec with { SomeProp = false };
  }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,在 C# 10 中(在撰写本文时处于预览状态)我注意到可以DoSomething3编译。C# 10 引入了record structsrecord classes. 后者是默认值。看来我所追求的对于record struct对象来说是可能的,但对于record class对象来说却不是。换句话说,在示例中,DoSomething3不能使用 aSomeRecord作为参数来调用,除非SomeRecord更改为 a record struct

我没有找到一种方法可以对record class我的用例中需要的 a 执行相同的操作。