2013-03-12 3 views
0

Я использую Roslyn с сентября 2012 года. Я пытаюсь создать экземпляр класса из файла. Проблема в том, что класс реализует и переопределяет некоторые методы. Когда я пытаюсь запустить во время выполнения компиляции получают ошибки как:Скомпилированный класс выполнения не может реализовать интерфейс - Roslyn

error CS0122: 'GameObject' is inaccessible due to its protection level Roslyn.Compilers.CSharp.Diagnostic 
error CS0115: 'rotate(float)': no suitable method found to override Roslyn.Compilers.CSharp.Diagnostic 

Это выглядит как класс не видит интерфейс и верховные функции. Но мой сборник выглядит следующим образом:

var comp = Compilation.Create("Test.dll" 
      , syntaxTrees: new[] { syntaxTree } 
      , references: new[] { 
       MetadataFileReference.CreateAssemblyReference("mscorlib"), 
       new MetadataFileReference(typeof(Game.IGameObjectInterface).Assembly.Location), 
       new MetadataFileReference(typeof(Team).Assembly.Location), 
       new MetadataFileReference(typeof(System.Linq.Enumerable).Assembly.Location), 
       new MetadataFileReference(typeof(LinkedList<>).Assembly.Location), 

      } 
      , options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary) 
      ); 

Ссылка на интерфейс добавлена.

Что я делаю неправильно?

EDIT GameObject

abstract class GameObject: IGameObject { 
    protected string name; 
    protected Entity entity; 
     . 
     . 
     . 
    //Look here create file load file 
    static GameObject() { 
     gameActionsPermitions = new Dictionary<string, List<IStaticGameObject>>(); 
     gameActions = new Dictionary<string, IGameAction>(); 
     IGameAction o = (IGameAction)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("Strategy.GroupControl.Game_Objects.GameActions.Produce"); 
     gameActions.Add(o.getName(), o); 
     gameActionsPermitions.Add(o.getName(), new List<IStaticGameObject>()); 
    } 

     . 
     . 
     . 


    public abstract void rotate(float f); 
    public abstract void nonActiveRotate(float f); 
    protected abstract void onDisplayed(); 


     . 
     . 
     . 

    } 

И inteface IGameObject

interface IGameObject{ 
    void rotate(float f); 
    void nonActiveRotate(float f); 
    void changeVisible(bool visible); 
    string getName(); 
    string getMesh(); 
    bool tryExecute(string executingAction); 

    Team Team { get; set; } 

} 

И функция из файла

public override void rotate(float f) { 
     tryExecute("Produce"); 
     sceneNode.Roll(new Mogre.Degree((float)(mFlySpeed * 0.5 *f))); 
     //position in LinkedList now moving 
     if (!mFlying) { 
      if (nextLocation()) { 
       mFlying = true; 
       mDestination = circularPositions.First.Value; //get the next destination. 
       prepareNextPosition(); 
       //update the direction and the distance 
       mDirection = mDestination - sceneNode.Position; 
       mDistance = mDirection.Normalise(); 
      } else { 
      }//nothing to do so stay in position  
     } else { 
      double move = mFlySpeed * f; 
      mDistance -= move; 
      if (mDistance <= .0f) { //reach destination 
       travelledInvisible = 0; 
       sceneNode.Position = mDestination; 
       mDirection = Mogre.Vector3.ZERO; 
       mFlying = false; 
      } else { 
       sceneNode.Translate(mDirection * (float)move); 
      } 
     } 
    } 

EDIT2:

файл с классом

using System; 
using System.Collections.Generic; 
using System.Linq; 
using Mogre; 
using Strategy.TeamControl; 



namespace Strategy.GroupControl.Game_Objects.StaticGameObjectBox { 
class Planet : GameObject { 

    protected double mDistance = 0.0f; //distance to positoin 
    protected Mogre.Vector3 mDirection = Mogre.Vector3.ZERO; // The direction the object is moving 

    protected bool mFlying = false; //bool to detect if object walking or stay 
    protected double mFlySpeed = 200f; //speed of planet 

    protected double travelledInvisible; 


    private static Random random = new Random(); 

    ///testing 
    public Planet() { 

    } 
    public Planet(string s) { 
     name = s; 
    } 
    //end 

    public Planet(string name, string mesh, Team myTeam, Mogre.SceneManager manager, double distanceFromCenter, 
     Vector3 center, int circularNum = 30) { 
     this.name = name; 
     this.mesh = mesh; 
     planetTeam = myTeam; 
     this.manager = manager; 

     //prepare list of positions 
     circularPositions = calculatePositions(circularNum, distanceFromCenter,center); 
     randomizeStartPosition(circularNum); // randomize start position 
     mDestination = circularPositions.First(); 

     //Mogre inicialization of object 
     entity = manager.CreateEntity(name, mesh); 
    } 

    /// <summary> 
    /// Rotating in visible mood, it means when planet is in active solar system 
    /// </summary> 
    /// <param name="f">delay between frames</param> 
    public override void rotate(float f) { 
     tryExecute("Produce"); 
     sceneNode.Roll(new Mogre.Degree((float)(mFlySpeed * 0.5 *f))); 
     //position in LinkedList now moving 
     if (!mFlying) { 
      if (nextLocation()) { 
       mFlying = true; 
       mDestination = circularPositions.First.Value; //get the next destination. 
       prepareNextPosition(); 
       //update the direction and the distance 
       mDirection = mDestination - sceneNode.Position; 
       mDistance = mDirection.Normalise(); 
      } else { 
      }//nothing to do so stay in position  
     } else { 
      double move = mFlySpeed * f; 
      mDistance -= move; 
      if (mDistance <= .0f) { //reach destination 
       travelledInvisible = 0; 
       sceneNode.Position = mDestination; 
       mDirection = Mogre.Vector3.ZERO; 
       mFlying = false; 
      } else { 
       sceneNode.Translate(mDirection * (float)move); 
      } 
     } 
    } 

    /// <summary> 
    /// Function calculate moves in invisible mode 
    /// </summary> 
    /// <param name="f">delay between frames</param> 
    public override void nonActiveRotate(float f) { 
     tryExecute("Produce"); 
     if (!mFlying) { 
      if (nextLocation()) { 
       mFlying = true; 
       mDestination = circularPositions.First.Value; //get the next destination. 
       prepareNextPosition(); 
       mDistance = mDirection.Normalise(); 
      } else { 
      }//nothing to do so stay in position  
     } else { 
      double move = mFlySpeed * f; 
      mDistance -= move; 
      if (mDistance <= .0f) { //reach destination 
       travelledInvisible = 0; 
       mDirection = Mogre.Vector3.ZERO; 
       mFlying = false; 

      } else { 
       travelledInvisible += move; 
      } 
     } 
    } 


    //own functions 

    /// <summary> 
    /// Randomize starting position of planet 
    /// </summary> 
    /// <param name="max">max of rotates</param> 
    private void randomizeStartPosition(int max) { 
     for (int i = 0; i < getRandomNumber(max); i++) { 
      prepareNextPosition(); 
     } 
    } 

    private static int getRandomNumber(int max) { 
     return random.Next(max); 
    } 

    /// <summary> 
    /// Cyclic remove from LinkedList and add on the end 
    /// </summary> 
    private void prepareNextPosition() { 
     var tmp = circularPositions.First; //save the node that held it 
     circularPositions.RemoveFirst(); //remove that node from the front of the list 
     circularPositions.AddLast(tmp); //add it to the back of the list. 
    } 

    /// <summary> 
    /// Calculate posistion on circle represent as ngon 
    /// </summary> 
    /// <param name="circularNum">Number of positions on circle</param> 
    /// <param name="distanceFromCenter">radius on circle</param> 
    /// <returns>linkedList with position on ngon (circle)</returns> 
    private LinkedList<Mogre.Vector3> calculatePositions(int circularNum, double distanceFromCenter,Vector3 center) { 
     var list = new LinkedList<Mogre.Vector3>(); 
     for (int i = 0; i < circularNum; i++) { 
      double x = System.Math.Cos(i * 2 * System.Math.PI/circularNum) * distanceFromCenter; 
      double y = System.Math.Sin(i * 2 * System.Math.PI/circularNum) * distanceFromCenter; 
      list.AddFirst(new Mogre.Vector3((float)x + center.x, 0, (float)y)+ center.y); 
     } 

     return list; 
    } 


    /// <summary> 
    /// The NextLocation() check if exist next location to move 
    /// </summary> 
    /// <returns>true ->exist/false -> not exist</returns> 
    private bool nextLocation() { 
     if (circularPositions.Count == 0) { 
      return false; 
     } 
     return true; 
    } 

    /// <summary> 
    /// Called when object is displayed (invisible to visible) 
    /// </summary> 
    protected override void onDisplayed() { 
     sceneNode.Position = mDestination; 
     mFlying = false; //jump correction 
    } 

}}

+0

Похоже, что вы ошибаетесь, используя GameObject в позиции, которая незаконно расширила бы его область доступности, и вы пометили метод как переопределяющий, когда он не переопределит что-либо. Мы не можем сказать об этом, не видя «GameObject» и «rotate». –

+0

Я добавил прототип 'GameObject' с' rotate'. – wolen

+0

И является ли функция в файле в классе, который фактически расширяет GameObject? –

ответ

1

Они выглядят как стандартные ошибки компилятора.

Я подозреваю, что ваш класс GameObject не указан как public. Это приведет к тому, что он не станет видимым для сборки, которую вы создаете через Roslyn, поскольку он компилирует новую (отдельную) сборку из той, в которой определены ваши типы.

Если вы делаете свои типы общедоступными, эта ошибка, скорее всего, исчезнет.

+0

И когда я создаю этот класс 'public', я должен создать каждый класс, который использует этот' public' class также 'public'? – wolen

+0

@wolen Нет - но любой класс, используемый вне этой сборки, должен быть общедоступным. –

+0

'var result = comp.Emit (moduleBuilder);' 'Success = true' Спасибо – wolen

Смежные вопросы