c# вопросец

Все, что вы хотели знать о программизме, но боялись спросить.
Ответить
dEBUGER
Частый Гость
Сообщения: 23
Зарегистрирован: 26 фев 2003, 15:01
Откуда: Toronto

c# вопросец

Сообщение dEBUGER »

Как продекларировать/инстанциировать член класса
как ссылку на обьект?

С++ анаолог:

Код: Выделить всё

class X
{
  string & _rStr;
  public:
  X(string& s) : _rStr(s)
  {}
} 

неработающий пример на с#:

Код: Выделить всё


  class Reflection
  {
        public Reflection (ref string f_s)
        {
            m_s = f_s;
        }
        
        private string m_s = null; // THIS IS WRONG! But how is right?

        public string Str
        {
            get{ return m_s; }
        }
    }

    class MainClass
    {
       [STAThread]
       static void Main(string[] args)
      {
            string m = "Master";
            Reflection r = new Reflection(ref m);
            Console.WriteLine("Object: {0}, Reflection {1}", m, r.Str);

            m = "Lomaster";
            Console.WriteLine("Object: {0}, Reflection {1}", m, r.Str);
            Console.ReadLine();
       }
    }
Аватара пользователя
apkbox
Пользователь
Сообщения: 78
Зарегистрирован: 22 мар 2003, 21:43
Откуда: Ottuda

Сообщение apkbox »

That is because m in 'm = "Lomaster"' becomes a new object, not the same object with an internal reference to a new string.
Semantic of references in c++ and IL is different.

This is one of solutions of the problem.

Код: Выделить всё

using System;

	public class xstring
	{
		private string _v;
		public xstring( string v )
		{
			_v = v;
		}

		public string value
		{
			get {
				return _v;
			}
			set {
				_v = value;
			}
		}
	}

class Reflection 
  { 
        public Reflection ( xstring f_s) 
        { 
            m_s = f_s; 
        } 
        
        private xstring m_s;

        public string Str 
        { 
            get{ return m_s.value; } 
        } 
    } 

    class MainClass 
    { 
       [STAThread] 
       static void Main(string[] args) 
      { 
            xstring m = new xstring( "Master" ); 
            Reflection r = new Reflection( m ); 
            Console.WriteLine("Object: {0}, Reflection {1}", m.value, r.Str); 

            m.value = "Lomaster"; 
            Console.WriteLine("Object: {0}, Reflection {1}", m.value, r.Str); 
            Console.ReadLine(); 
       } 
    }
dEBUGER
Частый Гость
Сообщения: 23
Зарегистрирован: 26 фев 2003, 15:01
Откуда: Toronto

Сообщение dEBUGER »

Thanx man,

I knew this solution and disregarded it as an awkward, but I guess I got to use it, so thanks anyway.

D.
Ответить