日期:2014-05-20  浏览次数:21194 次

一段比较值类型与引用类型的代码,请指教,出现问题,请帮忙
值类型StructComplex.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace StructComplex
{
  class StructComplex
  {
  public struct StructComplex
  {
  public int Real;
  public int Imaginary;

  public static StructComplex AddComplex(StructComplex S1, StructComplex S2)
  { StructComplex result;

  result.Real = S1.Real + S2.Real;
  result.Imaginary = S1.Imaginary + S2.Imaginary;
  return result;
  }

  public StructComplex ChangeVal(StructComplex r1)
  { r1.Real += this.Real;
  r1.Imaginary += this.Imaginary;
  return r1;
  }


  public StructComplex(int i, int m)

  {
  Real = i;
  Imaginary= m;
   
  }
   
   
   
   
  }
  }
}
引用类型ClassComplex.cs
using System;
using System.Collections.Generic;
using System.Text;
class ClassComplex
{
  public class ClassComplex
  {
  public int Real;
  public int Imaginary;

  public static ClassComplex AddComplex(ClassComplex C1, StructComplex C2)
  {
  ClassComplex result;

  result.Real = C1.Real + C2.Real;
  result.Imaginary = C1.Imaginary + C2.Imaginary;
  return result;
  }

  public ClassComplex ChangeVal(ClassComplex r1)
  {
  r1.Real += this.Real;
  r1.Imaginary += this.Imaginary;
  return r1;
  }


  public ClassComplex(int x, int y)

  {
  Real = x;
  Imaginary =y;
   
  }




  }
  }



Program.cs
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
  static void Main(string[] args)
  {
  StructComplex s1 = new StructComplex(1,5);
  StructComplex s2 = new StructComplex(5,10);
   
  //s1.Real = 1;
  //s1.Imaginary = 5;
  //s2.Real = 5;
  //s2.Imaginary = 10;
  StructComplex result1 = StructComplex.AddComplex(s1, s2);
  Console.WriteLine("{0}+{1}i",result1.Real,result1.Imaginary );
  StructComplex result2=s1.ChangeVal(result1);
  Console.WriteLine("{0}+{1}i,{2}+{3}i",result1.Real,result1.Imaginary ,result2.Real,result2.Imaginary );

  ClassComplex c1 = new ClassComplex();
  ClassComplex c2 = new ClassComplex();
  ClassComplex cr1, cr2;
  c1.Real = 2;
  c1.Imaginary = 6;
  c2.Real = 6;
  c2.Imaginary = 10;
  cr1=ClassComplex.AddComplex(c1, c2);
  Console.WriteLine("{0}+{1}i", cr1.Real,cr1.Imaginary);
  cr2=c1.ChangeVal(cr1);
  Console.WriteLine("{0}+{1}i,{2}+{3}i", cr1.Real,cr1.Imaginary , cr2.Real,cr2.Imaginary);

  }
}


错误类型为:
错误 1 “StructComplex”: 成员名称不能与它们的封闭类型相同 E:\C#.net\StructComplex\StructComplex\StructComplex.cs 9 23 StructComplex