通过接口

时间:2018-04-12 22:57:32

标签: c# interface ironpython

我正在使用IronPython从正在运行的应用程序访问.net(C#)类实例,但我试图使用Interface限制只访问类中的方法和属性。这不起作用,因为我的Python可以访问所有公共方法和原因。

我已经创建了一个小型测试应用程序来演示此问题并尝试使用可能的解决方案,但到目前为止,它与我更大的生产应用程序存在同样的问题。

我的类实例正在通过ScriptScope.SetVariable(" TestApp",这个)与Python共享,这很好。

相关的C#代码如下:

using System;
using Microsoft.Scripting.Hosting;
using System.Collections.Generic;
using IronPython.Hosting;

namespace PythonTestObj
{
    public class PythonScriptRun
    {

        // Bunch of Python code here.  Not relevent

        public ITest GetProp()
        {
            ITest retVal = (ITest) _TestClass;
            return retVal;
        }

        public interface ITest
        {
            string HelloWorld { get; }
        }

        public class TestClass : ITest
        {
            public string HelloWorld
            {
                get
                {
                    return "Hello World";
                }
            }

            public string GoodbyeWorld
            {
                get
                {
                    return "Goodbye World";
                }
            }
        }
    }
}

以下是我的Python脚本:

import System
import clr
import sys

clr.AddReference("PythonTestObj.dll")
from PythonTestObj import *

engOp = globals().get('TestApp')

#engOp now refers to an instance of TestClass through an ITest interface

# This print should work as HelloWorld is in the ITest
retStr = engOp.GetProp().HelloWorld
print retStr

# This should fail because GoodbuyWorld is not in ITest
retStr = engOp.GetProp().GoodbyeWorld
print retStr

当我运行这个python脚本时,我得到以下输出:

Hello World
Goodbye World

由于GetProp()方法返回了一个ITest界面,我对如何找到GoodbyeWorld属性感到茫然!

问题:有没有办法做到这一点,还是我咆哮错误的树?

0 个答案:

没有答案
相关问题