【问题标题】:how to set template in c#如何在c#中设置模板
【发布时间】:2021-09-25 09:45:39
【问题描述】:

如何通过模板模板在 Sprite 中设置 id

public class templa<T> where T : class , new(){
    public T CreateMe(){
        T temp = new T();
        shortInt si
        si.Set(2, 2);
        //T needs to have id as shortInt else it won't work
        
        temp.id = si; // temp = si// doesn't work either
        return temp;
    }
}
public struct shortInt{
    public short s;
    public int i;
    public void Set(short s, int i){
        this.s = s;
        this.i = i;
    }
}

这里的 Sprite 有 id 这是我试图通过模板更改 id 来实现的目标

public class Sprite{
    public Sprite(){}
    public shortInt id;
    set{
        id = value;
    }
}

我在网上搜索,发现只能用 { get;放; } 我在这里一无所知

【问题讨论】:

标签: c# templates set


【解决方案1】:

使用where(generic type constraint)

这样的代码

 public class Templat<T> where T :
     Sprite, new()  //constraint in here
    {
        public T CreateMe()
        {
            T temp = new T();
            shortInt si = new shortInt();
            si.Set(2, 2);

            temp.id = si;
            return temp;
        }

    }

    public struct shortInt
    {
        public short s;
        public int i;
        public void Set(short s, int i)
        {
            this.s = s;
            this.i = i;
        }
    }

    public class Sprite
    {
        public Sprite() { }
        public shortInt id { get; set; }
    }

【讨论】:

  • 明白了,谢谢:public class Templat where T : Sprite, new() 已经完成了它的工作,我一直在寻找你的代码来寻找问题,谢谢
猜你喜欢
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 2022-01-05
  • 2013-04-16
  • 2020-07-27
  • 2023-04-07
相关资源
最近更新 更多