ref and out parameters in C# and cannot be marked as variant

后端 未结 4 1982
-上瘾入骨i
-上瘾入骨i 2020-11-29 05:09

What does the statement mean?

From here

ref and out parameters in C# and cannot be marked as variant.

1) Does it mean

4条回答
  •  野性不改
    2020-11-29 05:28

    Eric Lippert has a great explanation of why this constraint exists.

    If you are looking to work around this limitation. You can do it like this:

    public static class ResultExtension{
        public static bool TryGetValue(this IResult self, out T res) {
            if (self.HasValue) {
                res = self.Value;
                return true;
    
            }
            res = default;
            return false;
        }
    }
    
    public interface IResult
    {
        bool HasValue { get; }
        T Value { get; }
    }
    

    This works because there are two structures. One structure gets the covariance and the other gets the out parameter. The out parameter is not marked as variant so the compiler is happy.

提交回复
热议问题