相关疑难解决方法(0)

编译错误.在struct中使用属性

请解释struct构造函数的以下错误.如果我将struct更改为class,那么错误就会消失.

public struct DealImportRequest
{
    public DealRequestBase DealReq { get; set; }
    public int ImportRetryCounter { get; set; }

    public DealImportRequest(DealRequestBase drb)
    {
        DealReq = drb;
        ImportRetryCounter = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 错误CS0188:在分配所有字段之前,不能使用'this'对象
  • 错误CS0843:在将控制权返回给调用者之前,必须完全分配自动实现的属性"DealImportRequest.DealReq"的备份字段.考虑从构造函数初始化程序中调用默认构造函数.

c# language-features struct compiler-errors

12
推荐指数
1
解决办法
2885
查看次数

这个C#结构的大小是多少?

存储在一个List<DataPoint>?是12个字节还是16个字节?

public struct DataPoint
{
    DateTime time_utc;
    float value;
}
Run Code Online (Sandbox Code Playgroud)

C#中有任何sizeof函数吗?

c# struct sizeof

10
推荐指数
3
解决办法
2万
查看次数

无法编译结构

以下代码表明我不能在结构中使用隐式属性:

public struct LimitfailureRecord
{
   public LimitfailureRecord(string sampleCode)
   {
      SampleCode = sampleCode;
   }

   public string SampleCode {get; set;}
   {
   }
}
Run Code Online (Sandbox Code Playgroud)

它无法编译,并显示错误消息

"在将控制权返回给调用者之前,必须完全分配自动实现的属性'blahblah.LimitfailureRecord.SampleCode'的后备字段.考虑从构造函数初始化程序调用默认构造函数."

如果我将结构更改为类,那很好.我需要做什么才能使它作为结构工作?如果我可以避免它,我宁愿不去支持字段的长度(这是真正代码的严重剥离版本).

c#

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

将公共只读字段用于不可变结构而不是私有字段/公共getter对

这是我第一次编写将用于广泛几何计算的小型不可变结构.我很想使用public readonly字段而不是private field/public getter组合.

public struct Vector4
{
    public readonly float Angle, Velocity;

    // As opposed to:
    private float _Angle, _Velocity;
    public float Angle { get { return (this._Angle); } }
    public float Velocity { get { return (this._Velocity); } }

    public Vector4 (float angle, float velocity)
    {
        // Once set in the constructor, instance values will never change.
        this.Angle = angle;
        this.Velocity = velocity;
    }
}
Run Code Online (Sandbox Code Playgroud)

它看起来更清洁,并消除了额外的层(吸气剂).如果不使用公共字段是不好的做法,那么以这种方式使用公共只读字段是否有任何负面影响?

请注意,我们只讨论价值类型.例如,数组会通过调用代码来覆盖要覆盖的元素.

更新:

感谢所有的投入.对于没有使用public readonly数据绑定等的情况,使用字段似乎没有任何缺点.在我的基准测试中,执行时间下降了70%,这是一个大问题.针对.NET 4,我原本期望编译器内联getter-only属性.基准测试当然是在发布配置中测试的,没有附加调试器.

.net c# field readonly getter-setter

4
推荐指数
2
解决办法
1151
查看次数

带有new和get整数的C#构造函数

这是Unity 5.5.0上的一个结构我对c#很新,并且不了解属性和结构.

这给出了在分配期间的错误this.X.

我假设您不能更改结构上的值,而关键字this指的是结构的属性

在将控制权返回给调用者之前,必须完全分配自动实现的属性"Point.X"的备份字段.考虑从构造函数初始化程序中调用默认构造函数.(CS0843)(Assembly-CSharp)[LN 15]

在将所有字段分配给(CS0188)之前不能使用'this'对象(Assembly-CSharp)[LN 16]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public struct Point 
{

    // Don't undertstand why "public int X, Y" works fine but not this        
    public int X { get; set; }

    public int Y { get; set; }

    //public int X,Y;

    public Point(int x, int y) 
    { 
        // LN 15
        this.X=x;
        this.Y=y;
    }
}
Run Code Online (Sandbox Code Playgroud)

c#

2
推荐指数
1
解决办法
330
查看次数