コード例 #1
0
        public UnityEngine.GameObject __Gen_Delegate_Imp20(StructTest p0, int p1, object p2)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int err_func   = LuaAPI.load_error_func(L, errorFuncRef);
            ObjectTranslator translator = luaEnv.translator;

            LuaAPI.lua_getref(L, luaReference);

            translator.Push(L, p0);
            LuaAPI.xlua_pushinteger(L, p1);
            translator.PushAny(L, p2);

            int __gen_error = LuaAPI.lua_pcall(L, 3, 1, err_func);
            if (__gen_error != 0)
            {
                luaEnv.ThrowExceptionFromError(err_func - 1);
            }


            UnityEngine.GameObject __gen_ret = (UnityEngine.GameObject)translator.GetObject(L, err_func + 1, typeof(UnityEngine.GameObject));
            LuaAPI.lua_settop(L, err_func - 1);
            return(__gen_ret);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
コード例 #2
0
        public string __Gen_Delegate_Imp21(StructTest p0)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int err_func   = LuaAPI.load_error_func(L, errorFuncRef);
            ObjectTranslator translator = luaEnv.translator;

            LuaAPI.lua_getref(L, luaReference);

            translator.Push(L, p0);

            int __gen_error = LuaAPI.lua_pcall(L, 1, 1, err_func);
            if (__gen_error != 0)
            {
                luaEnv.ThrowExceptionFromError(err_func - 1);
            }


            string __gen_ret = LuaAPI.lua_tostring(L, err_func + 1);
            LuaAPI.lua_settop(L, err_func - 1);
            return(__gen_ret);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
コード例 #3
0
        public void __Gen_Delegate_Imp22(StructTest p0, object p1)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int err_func   = LuaAPI.load_error_func(L, errorFuncRef);
            ObjectTranslator translator = luaEnv.translator;

            LuaAPI.lua_getref(L, luaReference);

            translator.Push(L, p0);
            translator.PushAny(L, p1);

            int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func);
            if (__gen_error != 0)
            {
                luaEnv.ThrowExceptionFromError(err_func - 1);
            }



            LuaAPI.lua_settop(L, err_func - 1);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
コード例 #4
0
        public void SystemVoid(StructTest self, object go)
        {
#if THREAD_SAFT || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.L;
            int err_func   = LuaAPI.load_error_func(L, errorFuncRef);
            ObjectTranslator translator = luaEnv.translator;

            LuaAPI.lua_getref(L, luaReference);

            translator.Push(L, self);
            translator.PushAny(L, go);

            int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func);
            if (__gen_error != 0)
            {
                luaEnv.ThrowExceptionFromError(err_func - 1);
            }



            LuaAPI.lua_settop(L, err_func - 1);

#if THREAD_SAFT || HOTFIX_ENABLE
        }
#endif
        }
        public void DefaultConstructor_Struct()
        {
            Func <object> create = ExpressionReflectionDelegateFactory.Instance.CreateDefaultConstructor <object>(typeof(StructTest));

            StructTest m = (StructTest)create();

            Assert.IsNotNull(m);
        }
コード例 #6
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        StructTest _scp = target as StructTest;

        _scp.InitData();
    }
コード例 #7
0
        public void SerializeCompilerGeneratedMembers()
        {
            StructTest structTest = new StructTest
            {
                IntField       = 1,
                IntProperty    = 2,
                StringField    = "Field",
                StringProperty = "Property"
            };

            DefaultContractResolver skipCompilerGeneratedResolver = new DefaultContractResolver
            {
                DefaultMembersSearchFlags =
                    BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public
            };

            string skipCompilerGeneratedJson = JsonConvert.SerializeObject(
                structTest,
                Formatting.Indented,
                new JsonSerializerSettings {
                ContractResolver = skipCompilerGeneratedResolver
            }
                );

            StringAssert.AreEqual(
                @"{
  ""StringField"": ""Field"",
  ""IntField"": 1,
  ""StringProperty"": ""Property"",
  ""IntProperty"": 2
}",
                skipCompilerGeneratedJson
                );

            DefaultContractResolver includeCompilerGeneratedResolver = new DefaultContractResolver
            {
                DefaultMembersSearchFlags =
                    BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
                SerializeCompilerGeneratedMembers = true
            };

            string includeCompilerGeneratedJson = JsonConvert.SerializeObject(
                structTest,
                Formatting.Indented,
                new JsonSerializerSettings {
                ContractResolver = includeCompilerGeneratedResolver
            }
                );

            JObject o = JObject.Parse(includeCompilerGeneratedJson);

            Console.WriteLine(includeCompilerGeneratedJson);

            Assert.AreEqual("Property", (string)o["<StringProperty>k__BackingField"]);
            Assert.AreEqual(2, (int)o["<IntProperty>k__BackingField"]);
        }
コード例 #8
0
ファイル: TestDeepCloner.cs プロジェクト: swoo888/DeepClone
        public void RunStructTest1()
        {
            var s = new StructTest(1, "2")
            {
                Ignored = "3"
            };
            var c = cloner.Clone(s);

            Assert(s.Computed == c.Computed);
            Assert(c.Ignored == null);
        }
コード例 #9
0
        public void CreateSetWithBadTarget()
        {
            object structTest = new StructTest();

            Action <object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet <object>(typeof(StructTest).GetProperty("StringProperty"));

            setter(structTest, "Hi");

            Assert.AreEqual("Hi", ((StructTest)structTest).StringProperty);

            setter(new TimeSpan(), "Hi");
        }
コード例 #10
0
ファイル: TestSerialize.cs プロジェクト: garyhertel/Atlas
    public void SerializeStruct()
    {
        var input = new StructTest()
        {
            value = 5
        };

        _serializer.Save(Call, input);
        StructTest output = _serializer.Load <StructTest>(Call);

        Assert.AreEqual(input, output);
    }
コード例 #11
0
        public void ClassToStructMapping()
        {
            var mapper = new UltraMapper();

            var source = new Test();
            var target = new StructTest();

            mapper.Map(source, out target);

            var result = mapper.VerifyMapperResult(source, target);

            Assert.IsTrue(result);
        }
コード例 #12
0
        public void StructTestTests()
        {
            var faked = new StructTest {
                IntField       = 100,
                IntProperty    = 200,
                StringField    = "String Field",
                StringProperty = "String Property"
            };

            RunTestsOn(faked);

            Assert.Pass();
        }
コード例 #13
0
    private static void Main()
    {
        var c = new StructTest();

        c.Id             = 51;
        c.OtherId        = 52;
        c.MoreSpace      = 53;
        c.EvenMoreSpace  = 54;
        c.MoreThan64Byte = 55;
        Console.WriteLine("Attach the debugger now.");
        Console.ReadKey();
        Console.WriteLine(c.Id + c.OtherId + c.MoreSpace + c.EvenMoreSpace);
    }
コード例 #14
0
        private void button13_Click(object sender, EventArgs e)
        {
            Test tc = new Test();

            tc.i = 1000;
            TestClass(tc);
            MessageBox.Show(tc.i.ToString());

            StructTest t = new StructTest();

            t.i = 1000;
            TestStruct(t);
            MessageBox.Show(t.i.ToString());
        }
        public void SetOnStruct()
        {
            object structTest = new StructTest();

            Action <object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet <object>(typeof(StructTest).GetProperty("StringProperty"));

            setter(structTest, "Hi1");
            Assert.AreEqual("Hi1", ((StructTest)structTest).StringProperty);

            setter = ExpressionReflectionDelegateFactory.Instance.CreateSet <object>(typeof(StructTest).GetField("StringField"));

            setter(structTest, "Hi2");
            Assert.AreEqual("Hi2", ((StructTest)structTest).StringField);
        }
コード例 #16
0
        public void CreateSetWithBadTarget()
        {
            ExceptionAssert.Throws <InvalidCastException>(() =>
            {
                object structTest = new StructTest();

                var setter = DynamicReflectionDelegateFactory.Instance.CreateSet <object>(typeof(StructTest).GetProperty("StringProperty"));

                setter(structTest, "Hi");

                Assert.AreEqual("Hi", ((StructTest)structTest).StringProperty);

                setter(new TimeSpan(), "Hi");
            }, "Specified cast is not valid.");
        }
コード例 #17
0
        public void StructToClassMapping()
        {
            var mapper = new UltraMapper();

            var source = new StructTest()
            {
                DateTime = new DateTime(2013, 12, 18)
            };

            var target = mapper.Map <Test>(source);

            var result = mapper.VerifyMapperResult(source, target);

            Assert.IsTrue(result);
        }
コード例 #18
0
ファイル: TestClone.cs プロジェクト: garyhertel/Atlas
    public void CloneStruct()
    {
        var input = new StructTest()
        {
            value = 5
        };

        var output = _serializer.Clone(log, input);

        Assert.AreEqual(input, output);

        output.value = 2;

        Assert.AreNotEqual(input, output);
    }
コード例 #19
0
    public static void Main()
    {
        StructTest st1 = new StructTest();
        StructTest st2 = new StructTest();

        st1.Value = 1;
        st2.Value = 2;
        Console.WriteLine("st1.Value = " + st1.ToString());
        Console.WriteLine("st2.Value = " + st2.ToString());

        st1       = st2;
        st1.Value = 3;

        Console.WriteLine("st1.Value = " + st1.ToString());
        Console.WriteLine("st2.Value = " + st2.ToString());
    }
コード例 #20
0
        public static void StructTest6()
        {
            Dictionary <string, StructTest> m_dictAsset = new Dictionary <string, StructTest>();
            StructTest cube = new StructTest();

            cube.type          = "111";
            m_dictAsset["123"] = cube;
            cube.type          = "123";
            string strId = "123";

            if (!m_dictAsset.TryGetValue(strId, out cube)) //注释:这句代码报错,提示错误InvalidCastException: Specified cast is not valid
            {
                throw new Exception();
            }
            if (cube.type != "111")
            {
                throw new Exception();
            }
        }
コード例 #21
0
ファイル: xample1.cs プロジェクト: ErrorAlpaka/TDP
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //gameObject.AddComponent<MonoTest>(),
            //ClassTest classTest = new ClassTest();
            //classTest.SayHello();

            StructTest _structTest = new StructTest();
            // Hier wird die Methode "SayHello" auf der Instanz aufgerufen
            _classTest.SayHello();
            _structTest.SayHello();

            // Vector3 ist ein Positions / Movementgeber. wird hier erstellt
            Vector3 _pos = new Vector3(0f, 1f, 0f);

            // wendet Transformation von Vector3 an
            transform.position += _pos;
            //gleicher befehl v wie ^
            //transform.position = transform.position + offset
        }
    }
コード例 #22
0
        public void __Gen_Delegate_Imp24(StructTest p0, object p1)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int errFunc    = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
            ObjectTranslator translator = luaEnv.translator;
            translator.Push(L, p0);
            translator.PushAny(L, p1);

            PCall(L, 2, 0, errFunc);



            LuaAPI.lua_settop(L, errFunc - 1);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
コード例 #23
0
        public string __Gen_Delegate_Imp23(StructTest p0)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int errFunc    = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
            ObjectTranslator translator = luaEnv.translator;
            translator.Push(L, p0);

            PCall(L, 1, 1, errFunc);


            string __gen_ret = LuaAPI.lua_tostring(L, errFunc + 1);
            LuaAPI.lua_settop(L, errFunc - 1);
            return(__gen_ret);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
コード例 #24
0
        public UnityEngine.GameObject __Gen_Delegate_Imp22(StructTest p0, int p1, object p2)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int errFunc    = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
            ObjectTranslator translator = luaEnv.translator;
            translator.Push(L, p0);
            LuaAPI.xlua_pushinteger(L, p1);
            translator.PushAny(L, p2);

            PCall(L, 3, 1, errFunc);


            UnityEngine.GameObject __gen_ret = (UnityEngine.GameObject)translator.GetObject(L, errFunc + 1, typeof(UnityEngine.GameObject));
            LuaAPI.lua_settop(L, errFunc - 1);
            return(__gen_ret);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
コード例 #25
0
ファイル: handleref.cs プロジェクト: Zman0169/mono
	public static extern int mono_safe_handle_struct (StructTest test);
コード例 #26
0
ファイル: Manager.cs プロジェクト: learnUnity/KU_NET
	void OnGUI ()
	{
		GUILayout.Label ("process = " + value.ToString (), GUILayout.Width (150));

		GUILayout.Space (10);
		GUILayout.Label ("state = " + isDone, GUILayout.Width (150));
		GUILayout.Label ("HttpDownload :" , GUILayout.Width (150));
		GUILayout.Label ("Socket : " , GUILayout.Width (150));

		GUILayout.BeginHorizontal();
		if (GUILayout.Button ("Pause", GUILayout.Width (150))) {
			http.Pause ();
		}

		if(GUILayout.Button("Close Socket",GUILayout.Width(150)))
		{
			AsyncSocket asocket = client.GetSocket();

			asocket.CloseConnect();
		}

		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();

		if (GUILayout.Button ("Resume", GUILayout.Width (150))) {
			http.Resume ();
		}

		if (GUILayout.Button ("Send Struct Message", GUILayout.Width (150)))
		{
			MessageInfo.MessageType = MessageDataType.Struct;
			HeartBeatStructData mess;
			mess.boolValue = true;
			mess.charValue = 2;
			mess.doubleValue = 2.3;
			mess.floatValue = 1.5f;
			mess.info = "i'm fine @ ~~~ 你好";
			mess.msgID = 102;
			var head = new StructMessageHead ();
			head.CMD = 102;
			head.bodyLen = (UInt32)Marshal.SizeOf (mess);

			var message = StructMessage.Create (head, mess);

			client.Send<HeartBeatStructData> (message, delegate(HeartBeatStructData obj) {
				LogMgr.Log ("Struct Message Callback");
				KTool.Dump (obj);
			});
		}

		if (GUILayout.Button ("Send Json Message", GUILayout.Width (150)))
		{
			MessageInfo.MessageType = MessageDataType.Json;
			var test = new StructTest ();
			test.val.Add (123);
			test.val.Add (246);
			test.val.Add (45);
			var Jsonhead = new JsonMessageHead ();
			var jsonMessage = JsonMessage.Create<StructTest> (test, Jsonhead);
			client.Send<StructTest> (jsonMessage, delegate(StructTest obj) {
				LogMgr.Log ("Json Message Callback");
				KTool.Dump (obj);
				
			});


		}

		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();


		if (GUILayout.Button ("start", GUILayout.Width (150))) {

			string rootpath = Application.persistentDataPath;
			http.BeginDownLoadFileFlushToFile ("http://118.192.69.207:8083/monster.apk",rootpath + "/mons.assetbundle",
			delegate(byte[] arg1, float arg2, bool arg3) 
			{
					value = arg2;
					isDone = arg3;
				LogMgr.Log ("FlushToFile Onprocess " + "  float  =" + arg2.ToString () + " isDone " + arg3.ToString ());
				});
			
			http.StartConnect ();

//			http.BeginDownLoadFileFlushToMemory ("http://118.192.69.207:8083/monster.apk",rootpath + "/mons.apk",
//			delegate(byte[] arg1, float arg2, bool arg3)
//			{
//				value = arg2;
//				isDone = arg3;
//				LogMgr.Log ("FlushToMemory Onprocess " + "  float  =" + arg2.ToString () + " isDone " + arg3.ToString ());
//			});
//			
//			http.StartConnect ();
		}

		if(GUILayout.Button("Test Protobuf Serialize",GUILayout.Width(150)))
		{
			KprotobufMessage pmessage = new KprotobufMessage(){Id = 1235,data =new List<string>(new string[]{"hello","my name is cjsjy!"," welcome  中国!"})};
			string str= ParseUtils.ProtoBuf_Serialize<KprotobufMessage>(pmessage);
			LogMgr.Log("protobuf : "+str );
			var result = ParseUtils.ProtoBuf_Deserialize<KprotobufMessage>(str);
			
			LogMgr.Log(result);
			
		}

		if(GUILayout.Button("Send Protobuf ",GUILayout.Width(150)))
		{
			MessageInfo.MessageType = MessageDataType.ProtoBuf;
			KprotobufMessage pmessage = new KprotobufMessage(){Id = 1235,data =new List<string>(new string[]{"hello","my name is cjsjy!"," welcome  中国!"})};

			var Protbufhead = new ProtobufMessageHead ();
			var ProbufMessage = ProtobufMessage.Create<KprotobufMessage>(Protbufhead,pmessage);

			client.Send<KprotobufMessage>(ProbufMessage,delegate(KprotobufMessage obj) {
				LogMgr.Log ("Protobuf Message Callback");
				LogMgr.Log(obj);
			});

			
		}

		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();

		GUILayout.Label("",GUILayout.Width(150));

		if(GUILayout.Button("Reconnect Socket",GUILayout.Width(150)))
		{

			client.Reconnect();
			
		}

		GUILayout.EndHorizontal();
	}
コード例 #27
0
 /// <summary>Serialize the instance into the stream</summary>
 public static void Serialize(Stream stream, StructTest instance)
 {
     var msField = global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Pop();
     global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Push(msField);
 }
コード例 #28
0
 /// <summary>Helper: put the buffer into a MemoryStream and create a new instance to deserializing into</summary>
 public static StructTest Deserialize(byte[] buffer)
 {
     StructTest instance = new StructTest();
     using (var ms = new MemoryStream(buffer))
         Deserialize(ms, ref instance);
     return instance;
 }
コード例 #29
0
ファイル: HotfixTest2.cs プロジェクト: mengtest/Xlua_Notes
    // Use this for initialization
    void Start()
    {
        LuaEnv       luaenv       = new LuaEnv();
        HotfixCalc   calc         = new HotfixCalc();
        NoHotfixCalc ordinaryCalc = new NoHotfixCalc();

        //对比热更与不热更标签用时(毫秒),执行同样的一组循环
        int CALL_TIME = 100 * 1000 * 1000;
        var start     = System.DateTime.Now;

        for (int i = 0; i < CALL_TIME; i++)
        {
            calc.Add(2, 1);  //return a-b=1
        }
        var d1 = (System.DateTime.Now - start).TotalMilliseconds;

        Debug.Log("Hotfix using:" + d1);

        start = System.DateTime.Now;
        for (int i = 0; i < CALL_TIME; i++)
        {
            ordinaryCalc.Add(2, 1);
        }
        var d2 = (System.DateTime.Now - start).TotalMilliseconds;

        Debug.Log("No Hotfix using:" + d2);
        Debug.Log("drop:" + ((d1 - d2) / d1));
        Debug.Log("Before Fix: 2 + 1 = " + calc.Add(2, 1));                                                                     //热更变成减法了
        Debug.Log("Before Fix: Vector3(2, 3, 4) + Vector3(1, 2, 3) = " + calc.Add(new Vector3(2, 3, 4), new Vector3(1, 2, 3))); //向量减法
        luaenv.DoString(@"
            xlua.hotfix(CS.HotfixCalc, 'Add', function(self, a, b)
                return a + b
            end)
        ");
        Debug.Log("After Fix: 2 + 1 = " + calc.Add(2, 1));                                                                      //热更再变成加法
        Debug.Log("After Fix: Vector3(2, 3, 4) + Vector3(1, 2, 3) = " + calc.Add(new Vector3(2, 3, 4), new Vector3(1, 2, 3)));

        double num;
        string str = "hehe";
        int    ret = calc.TestOut(100, out num, ref str);

        Debug.Log("ret = " + ret + ", num = " + num + ", str = " + str); //返回值是100+3,num+=2,str被赋值wrong version
        //打印test out, self=这个类,打印传入的值
        luaenv.DoString(@"
            xlua.hotfix(CS.HotfixCalc, 'TestOut', function(self, a, c, go)
                    print('TestOut', self, a, c, go)
                    if go then error('test error') end
                    return a + 10 , a + 20, 'right version'
                end)
        ");
        str = "hehe";
        ret = calc.TestOut(100, out num, ref str);
        Debug.Log("ret = " + ret + ", num = " + num + ", str = " + str); //110 120 rightversion,第一个可以理解成C#只接受第一个返回值

        luaenv.DoString(@"
            xlua.hotfix(CS.HotfixCalc, {
                 Test1 = function(self)
                    print('Test1', self) --self不是实参,相当于this,但是可以指向表
                    return 1
                 end;
                 Test2 = function(self, a, b)  --out向外传参可以不写
                     print('Test1', self, a, b)
                     return a + 10, 1024, b
                 end;
                 Test3 = function(a)
                    print(a)
                    return 10
                 end;
                 Test4 = function(a)
                    print(a)
                 end;
                 Test5 = function(self, a, ...)
                    print('Test4', self, a, ...)
                 end
            })
        ");
        //泛型热更演示
        int    r1 = calc.Test1 <int>(); //无论什么类型都是返回1
        double r2 = calc.Test1 <double>();

        Debug.Log("r1:" + r1 + ",r2:" + r2);

        string ss = "heihei"; //ref必须初始化
        int    r3 = calc.Test2(r1, out r2, ref ss);

        Debug.Log("r1:" + r1 + ",r2:" + r2 + ",r3:" + r3 + ",ss:" + ss); //这里面return c#只能接受第一个参数,因为有out和ref所以,r2 r3能取到值

        r3 = HotfixCalc.Test3("test3");
        r3 = HotfixCalc.Test3(2);
        r3 = HotfixCalc.Test3(this);  //lua变成C#之后再执行,这里面就和C#脚本的this是一样的
        Debug.Log("r3:" + r3);
        HotfixCalc.Test4(this);
        HotfixCalc.Test4(2);
        calc.Test5(10, "a", "b", "c");
        calc.Test5(10, 1, 3, 5);

        Debug.Log("----------------------before------------------------");
        //Stateless比较适合无状态的类,有状态的话,你得通过反射去操作私有成员,也没法新增状态(field)。Stateless有个好处,可以运行的任意时刻执行替换。
        // Stateful的代价是会在类增加一个LuaTable类型的字段(中间层面增加,不会改源代码)。但这种方式是适用性更广,比如你不想要lua状态,可以在构造函数拦截那返回空。而且操作状态性能比反射操作C#私有变量要好,也可以随意新增任意的状态信息。缺点是,执行成员函数之前就new好的对象,接收到的状态会是空,所以需要重启,在一开始就执行替换。
        TestStateful(); //Stateful方式下你可以在Lua的构造函数返回一个table,然后后续成员函数调用会把这个table给传递过去。
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        luaenv.DoString(@"
            xlua.hotfix(CS.StatefullTest, {
                ['.ctor'] = function(csobj)  --构造函数固定写法
                    return {evt = {}, start = 0}
                end;
                set_AProp = function(self, v)
                    print('set_AProp', v)
                    self.AProp = v
                end;
                get_AProp = function(self)
                    return self.AProp
                end;
                get_Item = function(self, k)
                    print('get_Item', k)
                    return 1024
                end;
                set_Item = function(self, k, v)
                    print('set_Item', k, v)
                end;
                add_AEvent = function(self, cb)
                    print('add_AEvent', cb)
                    table.insert(self.evt, cb)
                end;
                remove_AEvent = function(self, cb)
                   print('remove_AEvent', cb)
                   for i, v in ipairs(self.evt) do
                       if v == cb then
                           table.remove(self.evt, i)
                           break
                       end
                   end
                end;
                Start = function(self)
                    print('Start')
                    for _, cb in ipairs(self.evt) do
                        cb(self.start, 2)
                    end
                    self.start = self.start + 1
                end;
                StaticFunc = function(a, b, c)
                   print(a, b, c)
                end;
                GenericTest = function(self, a)
                   print(self, a)
                end;
                Finalize = function(self)   --析构函数固定写法
                   print('Finalize', self)
                end
           })
        ");
        Debug.Log("----------------------after------------------------");
        TestStateful(); //在下面调用执行的
        luaenv.FullGc();
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();

        var genericObj = new GenericClass <double>(1.1);

        genericObj.Func1();
        Debug.Log(genericObj.Func2());
        //泛型类要指定类型后热更
        luaenv.DoString(@"
            xlua.hotfix(CS['GenericClass`1[System.Double]'], {  --数字代表几个参数,固定的泛型命名写法 Type.GetType Method (String)
                ['.ctor'] = function(obj, a)
                    print('GenericClass<double>', obj, a)
                end;
                Func1 = function(obj)
                    print('GenericClass<double>.Func1', obj)
                end;
                Func2 = function(obj)
                    print('GenericClass<double>.Func2', obj)
                    return 1314
                end
            })
        ");
        genericObj = new GenericClass <double>(1.1);
        genericObj.Func1();
        Debug.Log(genericObj.Func2());

        InnerTypeTest itt = new InnerTypeTest();

        itt.Foo();
        luaenv.DoString(@"
            xlua.hotfix(CS.InnerTypeTest, 'Bar', function(obj)
                    print('lua Bar', obj)
                    return {x = 10, y = 20}
                end)
        ");
        itt.Foo();

        StructTest st = new StructTest(gameObject);

        Debug.Log("go=" + st.GetGo(123, "john"));
        luaenv.DoString(@"
            xlua.hotfix(CS.StructTest, 'GetGo', function(self, a, b)
                    print('GetGo', self, a, b)
                    return nil
                end)
        ");
        Debug.Log("go=" + st.GetGo(123, "john"));

        GenericStruct <int> gs = new GenericStruct <int>(1);

        Debug.Log("gs.GetA()=" + gs.GetA(123));
        luaenv.DoString(@"
            xlua.hotfix(CS['GenericStruct`1[System.Int32]'], 'GetA', function(self, a)
                    print('GetA',self, a)
                    return 789
                end)
        ");
        Debug.Log("gs.GetA()=" + gs.GetA(123));

        try
        {
            calc.TestOut(100, out num, ref str, gameObject);
        }
        catch (LuaException e)
        {
            Debug.Log("throw in lua an catch in c# ok, e.Message:" + e.Message);
        }
    }
コード例 #30
0
ファイル: ContentHolder.cs プロジェクト: mbmccormick/Ximura
        public void ContentHolder_Test1()
        {
            string strData = "A bit fat hairy bloke.";
            ContentHolder<string> stringHolder = new ContentHolder<string>(strData);
            ContentHolder<string> stringHolderds = (ContentHolder<string>)stringHolder.Clone();

            byte[] blob1 = new byte[1000];
            ContentHolder<byte[]> byteHolder1 = new ContentHolder<byte[]>(blob1);
            ContentHolder<byte[]> byteHolder1ds = (ContentHolder<byte[]>)byteHolder1.Clone();

            byte[] blob2 = new byte[1000];
            blob2[0] = 3;
            ContentHolder<byte[]> byteHolder2 = new ContentHolder<byte[]>(blob2);
            ContentHolder<byte[]> byteHolder2ds = (ContentHolder<byte[]>)byteHolder2.Clone();

            StructTest t1 = new StructTest() { Data = "78", Count = 8 };
            ContentHolder<StructTest> byteHolder3 = new ContentHolder<StructTest>(t1);
            ContentHolder<StructTest> byteHolder3ds = (ContentHolder<StructTest>)byteHolder3.Clone();

            ClassTest t2 = new ClassTest() { Data = "78", Count = 8 };
            ContentHolder<ClassTest> byteHolder4 = new ContentHolder<ClassTest>(t2);
            ContentHolder<ClassTest> byteHolder4ds = (ContentHolder<ClassTest>)byteHolder4.Clone();

        } 
コード例 #31
0
ファイル: Program.cs プロジェクト: jinibyun/CodkingLearn_Dec
        private static void Basic()
        {
            // 1. DataType
            Console.WriteLine("=================== Data Type ================");
            var dt = new DataType();

            dt.Test();

            // 2. Variable And Constant
            Console.WriteLine("=================== Variable & Constant ================");
            var vnc = new VariableAndConstant();

            vnc.Test();

            // 3. Array
            Console.WriteLine("=================== Array ================");
            var arr = new ArrayTest();

            arr.Test();

            // 4. String
            Console.WriteLine("=================== String ================");
            var strTest = new StringTest();

            strTest.Test();

            // 5. Enum
            Console.WriteLine("=================== Enum ================");
            var enumTest = new EnumTest();

            enumTest.Test();

            // 6. Operator
            Console.WriteLine("=================== Operator ================");
            var operatorTest = new OperatorTest();

            operatorTest.Test();

            // 7. If
            Console.WriteLine("=================== If ================");
            var ifTest = new IfTest();

            ifTest.Test();

            // 8. loop
            Console.WriteLine("=================== Loop ================");
            var loopTest = new LoopTest();

            loopTest.Test();

            // 9. yield keword: when collection data can be returned one by one in turn
            Console.WriteLine("=================== yield return ================");
            var yieldReturnTest = new yieldTest();

            yieldReturnTest.Test();

            // 10. Exception
            Console.WriteLine("=================== Exception ================");
            var exceptionTest = new ExceptionTest();

            exceptionTest.Test(0, 0);

            // 11. Struct
            Console.WriteLine("=================== Struct ================");
            var structTest = new StructTest();

            structTest.ToString();

            // 12. Nullable
            Console.WriteLine("=================== Nullable ================");
            var nullableTest = new NullableTest();

            nullableTest.Test(null, null, DateTime.Now, null);

            // 13. Method
            Console.WriteLine("=================== Method ================");
            var methodTest = new MethodTest();
            // 13-1
            int val = 1000;

            methodTest.TestPassByValue(val);

            Console.WriteLine("variable val's value is not changed: {0}", val);
            // 13-2
            int    x   = 0;
            double y   = 1.0;
            double ret = methodTest.TestPassByRef(ref x, ref y);

            Console.WriteLine("variable val's value is actually changed: x: {0} y: {1}", x, y);

            Console.WriteLine(x);
            Console.WriteLine(y);

            // 13-3
            int  c, d;
            bool bret = methodTest.TestPassByOut(10, 20, out c, out d);

            Console.WriteLine("variable val's value is actually changed: c: {0} d: {1}", c, d);

            // differenc between ref keyword and out keyword

            // 13-4.
            var returnValue = methodTest.TestDefaultParam(1, 2);

            Console.WriteLine("Default parameter test: " + returnValue);
            var returnValue2 = methodTest.TestDefaultParam(1, 2, "-----");

            // 13-5.
            var returnParamsValue = methodTest.TestParams(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

            Console.WriteLine("params keyword test: " + returnParamsValue);
        }
コード例 #32
0
 /// <summary>Helper: Serialize with a varint length prefix</summary>
 public static void SerializeLengthDelimited(Stream stream, StructTest instance)
 {
     var data = SerializeToBytes(instance);
     global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, (uint)data.Length);
     stream.Write(data, 0, data.Length);
 }
コード例 #33
0
 /// <summary>Serialize the instance into the stream</summary>
 public static void Serialize(Stream stream, StructTest instance)
 {
 }
コード例 #34
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static StructTest DeserializeLengthDelimited(Stream stream)
 {
     StructTest instance = new StructTest();
     DeserializeLengthDelimited(stream, ref instance);
     return instance;
 }
コード例 #35
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static StructTest DeserializeLength(Stream stream, int length)
 {
     StructTest instance = new StructTest();
     DeserializeLength(stream, length, ref instance);
     return instance;
 }
コード例 #36
0
ファイル: Program.cs プロジェクト: DavidLees/DesignPatterns
        static void Main(string[] args)
        {
            #region Patterns
            //factory patterns
            RunSimpleFactory();
            RunAbstrctMethodFactory();

            //Singleton pattern
            RunSingleton();
            #endregion

            #region StructVSClass
            //Struct vs Class

            TestStruct testStruct = new TestStruct();
            TestClass  testClass  = new TestClass();

            testStruct.x = 1;
            testClass.x  = 1;

            StructTest.TakeClass(testClass);
            StructTest.TakeStruct(testStruct);

            Console.WriteLine();
            Console.WriteLine("TestClass = {0} TestStruct = {1}", testClass.x, testStruct.x);
            #endregion

            #region index test
            //indexer test
            MyArray myTestArray = new MyArray();

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(myTestArray[i]);
            }

            for (int i = 0; i < 10 / 2; i++)
            {
                string s = myTestArray[i];
                myTestArray[i] = myTestArray[myTestArray.Length() - i - 1];
                myTestArray[myTestArray.Length() - i - 1] = s;
            }

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(myTestArray[i]);
            }

            #endregion

            #region BookTest
            var             bookProcesser  = new BookProcessor();
            DBEventListener dbBookListener = new DBEventListener(bookProcesser.GetBookDb());

            PopulateBookProcessor(bookProcesser);

            string choice = string.Empty;

            do
            {
                choice = bookProcesser.BuyBook(new BookProcessor.OutOfStockDelegate(ProcessOutofStock));
            } while (choice != "q");


            #endregion BookTest

            #region FacadeTest
            Customer customerOne = new Customer("Bob Jones", 150000);
            Customer customerTwo = new Customer("Sally Smith", 90000);

            MortgageApprover mortgageApprove = new MortgageApprover();

            Console.WriteLine(
                mortgageApprove.CheckForApproval(customerOne)
                    ? "Customer {0} is approved!"
                    : "Custerom {0} is declined :(", customerOne.Name);

            Console.WriteLine(
                mortgageApprove.CheckForApproval(customerTwo)
                    ? "Customer {0} is approved!"
                    : "Custerom {0} is declined :(", customerTwo.Name);
            #endregion

            #region AdapterTest
            AdapterPattern adapterTest = new AdapterPattern();

            adapterTest.TestAdapterPattern();
            #endregion
        }
コード例 #37
0
 /// <summary>Serialize the instance into the stream</summary>
 public static void Serialize(Stream stream, StructTest instance)
 {
     using (var msField = new MemoryStream(0))
     {
     }
 }
コード例 #38
0
ファイル: HotfixTest2.cs プロジェクト: chen13469990/Racing
    // Use this for initialization
    void Start()
    {
        LuaEnv       luaenv       = new LuaEnv();
        HotfixCalc   calc         = new HotfixCalc();
        NoHotfixCalc ordinaryCalc = new NoHotfixCalc();

        int CALL_TIME = 100 * 1000 * 1000;
        var start     = System.DateTime.Now;

        for (int i = 0; i < CALL_TIME; i++)
        {
            calc.Add(2, 1);
        }
        var d1 = (System.DateTime.Now - start).TotalMilliseconds;

        Debug.Log("Hotfix using:" + d1);

        start = System.DateTime.Now;
        for (int i = 0; i < CALL_TIME; i++)
        {
            ordinaryCalc.Add(2, 1);
        }
        var d2 = (System.DateTime.Now - start).TotalMilliseconds;

        Debug.Log("No Hotfix using:" + d2);

        Debug.Log("drop:" + ((d1 - d2) / d1));

        Debug.Log("Before Fix: 2 + 1 = " + calc.Add(2, 1));
        Debug.Log("Before Fix: Vector3(2, 3, 4) + Vector3(1, 2, 3) = " + calc.Add(new Vector3(2, 3, 4), new Vector3(1, 2, 3)));
        luaenv.DoString(@"
            xlua.hotfix(CS.HotfixCalc, 'Add', function(self, a, b)
                return a + b
            end)
        ");
        Debug.Log("After Fix: 2 + 1 = " + calc.Add(2, 1));
        Debug.Log("After Fix: Vector3(2, 3, 4) + Vector3(1, 2, 3) = " + calc.Add(new Vector3(2, 3, 4), new Vector3(1, 2, 3)));

        double num;
        string str = "hehe";
        int    ret = calc.TestOut(100, out num, ref str);

        Debug.Log("ret = " + ret + ", num = " + num + ", str = " + str);

        luaenv.DoString(@"
            xlua.hotfix(CS.HotfixCalc, 'TestOut', function(self, a, c, go)
                    print('TestOut', self, a, c, go)
                    if go then error('test error') end
                    return a + 10, a + 20, 'right version'
                end)
        ");
        str = "hehe";
        ret = calc.TestOut(100, out num, ref str);
        Debug.Log("ret = " + ret + ", num = " + num + ", str = " + str);

        luaenv.DoString(@"
            xlua.hotfix(CS.HotfixCalc, {
                 Test1 = function(self)
                    print('Test1', self)
                    return 1
                 end;
                 Test2 = function(self, a, b)
                     print('Test1', self, a, b)
                     return a + 10, 1024, b
                 end;
                 Test3 = function(a)
                    print(a)
                    return 10
                 end;
                 Test4 = function(a)
                    print(a)
                 end;
                 Test5 = function(self, a, ...)
                    print('Test4', self, a, ...)
                 end
            })
        ");

        int    r1 = calc.Test1 <int>();
        double r2 = calc.Test1 <double>();

        Debug.Log("r1:" + r1 + ",r2:" + r2);

        string ss = "heihei";
        int    r3 = calc.Test2(r1, out r2, ref ss);

        Debug.Log("r1:" + r1 + ",r2:" + r2 + ",r3:" + r3 + ",ss:" + ss);

        r3 = HotfixCalc.Test3("test3");
        r3 = HotfixCalc.Test3(2);
        r3 = HotfixCalc.Test3(this);
        Debug.Log("r3:" + r3);
        HotfixCalc.Test4(this);
        HotfixCalc.Test4(2);
        calc.Test5(10, "a", "b", "c");
        calc.Test5(10, 1, 3, 5);

        Debug.Log("----------------------before------------------------");
        TestStateful();
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        luaenv.DoString(@"
            xlua.hotfix(CS.StatefullTest, {
                ['.ctor'] = function(csobj)
                    return {evt = {}, start = 0}
                end;
                set_AProp = function(self, v)
                    print('set_AProp', v)
                    self.AProp = v
                end;
                get_AProp = function(self)
                    return self.AProp
                end;
                get_Item = function(self, k)
                    print('get_Item', k)
                    return 1024
                end;
                set_Item = function(self, k, v)
                    print('set_Item', k, v)
                end;
                add_AEvent = function(self, cb)
                    print('add_AEvent', cb)
                    table.insert(self.evt, cb)
                end;
                remove_AEvent = function(self, cb)
                   print('remove_AEvent', cb)
                   for i, v in ipairs(self.evt) do
                       if v == cb then
                           table.remove(self.evt, i)
                           break
                       end
                   end
                end;
                Start = function(self)
                    print('Start')
                    for _, cb in ipairs(self.evt) do
                        cb(self.start, 2)
                    end
                    self.start = self.start + 1
                end;
                StaticFunc = function(a, b, c)
                   print(a, b, c)
                end;
                GenericTest = function(self, a)
                   print(self, a)
                end;
                Finalize = function(self)
                   print('Finalize', self)
                end
           })
        ");
        Debug.Log("----------------------after------------------------");
        TestStateful();
        luaenv.FullGc();
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();

        var genericObj = new GenericClass <double>(1.1);

        genericObj.Func1();
        Debug.Log(genericObj.Func2());
        luaenv.DoString(@"
            xlua.hotfix(CS['GenericClass`1[System.Double]'], {
                ['.ctor'] = function(obj, a)
                    print('GenericClass<double>', obj, a)
                end;
                Func1 = function(obj)
                    print('GenericClass<double>.Func1', obj)
                end;
                Func2 = function(obj)
                    print('GenericClass<double>.Func2', obj)
                    return 1314
                end
            })
        ");
        genericObj = new GenericClass <double>(1.1);
        genericObj.Func1();
        Debug.Log(genericObj.Func2());

        InnerTypeTest itt = new InnerTypeTest();

        itt.Foo();
        luaenv.DoString(@"
            xlua.hotfix(CS.InnerTypeTest, 'Bar', function(obj)
                    print('lua Bar', obj)
                    return {x = 10, y = 20}
                end)
        ");
        itt.Foo();

        StructTest st = new StructTest(gameObject);

        Debug.Log("go=" + st.GetGo(123, "john"));
        luaenv.DoString(@"
            xlua.hotfix(CS.StructTest, 'GetGo', function(self, a, b)
                    print('GetGo', self, a, b)
                    return nil
                end)
        ");
        Debug.Log("go=" + st.GetGo(123, "john"));

        GenericStruct <int> gs = new GenericStruct <int>(1);

        Debug.Log("gs.GetA()=" + gs.GetA(123));
        luaenv.DoString(@"
            xlua.hotfix(CS['GenericStruct`1[System.Int32]'], 'GetA', function(self, a)
                    print('GetA',self, a)
                    return 789
                end)
        ");
        Debug.Log("gs.GetA()=" + gs.GetA(123));

        try
        {
            calc.TestOut(100, out num, ref str, gameObject);
        }
        catch (LuaException e)
        {
            Debug.Log("throw in lua an catch in c# ok, e.Message:" + e.Message);
        }
    }
コード例 #39
0
 /// <summary>Helper: Serialize into a MemoryStream and return its byte array</summary>
 public static byte[] SerializeToBytes(StructTest instance)
 {
     using (var ms = new MemoryStream())
     {
         Serialize(ms, instance);
         return ms.ToArray();
     }
 }
コード例 #40
0
    private void RunTest(TestType testType, bool RunBaseLine = true)
    {
        PerformanceTest test       = null;
        int             iterations = int.Parse(inputField.text);

        switch (testType)
        {
        case TestType.Exception:
            test = new ExceptionTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Strings:
            test = new StringsTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Arrays:
            test = new ArraysTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Boxing:
            test = new BoxingTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.ForForeach:
            test = new ForForeachTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Struct:
            test = new StructTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Memory:
            test = new MemoryTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Instantiation:
            test = new InstantiationTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        case TestType.Properties:
            test = new PropertiesTest {
                RunBaseline = RunBaseLine, Iterations = iterations
            };
            break;

        default:
            throw new ArgumentOutOfRangeException(nameof(testType), testType, null);
        }

        titleText.text       = test.Name;
        descriptionText.text = test.Description;
        var averageResult = test.Measure();

        lastPerformanceResult = averageResult;
        UpdatePerformanceResultUI();

        var(perA, perB, perC) = GetPercentageOfResult(averageResult);
        totalASlider.value    = perA;
        totalBSlider.value    = perB;
        totalCSlider.value    = perC;
    }
コード例 #41
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static StructTest Deserialize(Stream stream)
 {
     StructTest instance = new StructTest();
     Deserialize(stream, ref instance);
     return instance;
 }
コード例 #42
0
 public static extern int mono_safe_handle_struct(StructTest test);