kittycat_13 2 / 2 / 0 Регистрация: 08.09.2014 Сообщений: 101 |
||||
1 |
||||
22.03.2015, 14:16. Показов 13632. Ответов 4 Метки нет (Все метки)
Здравствуйте. Такая проблема. Написала код, но программа выдает «System.Console» не содержит определение для «Writeline» (CS0117). Помогите, пожалуйста, исправить.
__________________
0 |
Заблокирован |
|
22.03.2015, 14:18 |
2 |
Console.WriteLine — L большая должна быть
0 |
2 / 2 / 0 Регистрация: 08.09.2014 Сообщений: 101 |
|
22.03.2015, 14:22 [ТС] |
3 |
Скажите, пожалуйста, а как сделать, чтобы окно консоли оставалось на экране, а то оно постоянно пропадает?
0 |
Заблокирован |
||||||||
22.03.2015, 14:25 |
4 |
|||||||
Добавьте после
0 |
Prizrak86 52 / 52 / 18 Регистрация: 20.03.2015 Сообщений: 278 |
||||||||
22.03.2015, 14:27 |
5 |
|||||||
Скажите, пожалуйста, а как сделать, чтобы окно консоли оставалось на экране, а то оно постоянно пропадает? В конце программы напиши
Программа будет ожидать нажатия клавиши «Enter», по нажатию которой программа закроется. Если написать
Программа будет ожидать нажатие любой клавиши, и закроется при нажатии на любую клавишу.
1 |
Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Getting the following error when typing trying to run code.
Game.cs(13,19): error CS0117: System.Console' does not contain a definition for
Writeline’
/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)
Map.cs(17,22): error CS1061: Type TreehouseDefence.Point' does not contain a definition for
x’ and no extension method x' of type
TreehouseDefence.Point’ could be found. Are you missing an assembly reference?
Code is as follows:
(Game.cs)
using System; namespace TreehouseDefence { class Game { public static void Main() { Map map = new Map(8, 5); Point point = new Point (4, 2); bool isOnMap = map.OnMap (point); Console.Writeline(isOnMap); point = new Point (8, 5); isOnMap = map.OnMap (point); Console.WriteLine (isOnMap); } } }
(map.cs)
namespace TreehouseDefence { class Map { public readonly int Width; public readonly int Height; public Map(int width, int height) { Width = width; Height = height; } public bool OnMap(Point point) { return point.x >= 0 && point.X < width && point.Y >=0 && point.Y < Height; } } }
3 Answers
seal-mask
STAFF
Hi there! It’s correct. There is no Writeline
in the System
class. There is, however, a WriteLine
in that class. Remember, capitalization matters here.
Hope this helps!
edited for additional information
If you’re still receiving an error about Point
, we will need to see your code in Point.cs
.
Jack Stone July 5, 2017 2:32pm
Still having the same error with the x point
namespace TreehouseDefence { class Point { public readonly int X; public readonly int Y; public Point (int x, int y) { X = x; Y = y; } } }
Jack Stone July 5, 2017 3:00pm
You’re a star.
Thank you very much.
Обе ошибки из-за того, что у вас нету нормальной ссылки на камеру. В первом случае вы подсунули newcam, что совпадает с названием вашего класса, а посему компилятор пытается интерпретировать это как вызов статического метода. Во втором случае вызов метода у camera не срабатывает, потому что вы взяли туториал трёхгодичной давности, а Component.camera уже давным-давно выпилили. Решить это всё можно двумя способами: обращаться к камере через Camera.main, либо сделать публичное поле и в инспекторе перетащить туда камеру.
Пригласить эксперта
1) У newcam нет метода WorldTo…. Какой вообще это тип данных?
2) Не найдена перегрузка с нужными параметрами для VIewportTOWorldPoint. Параметры не те в функцию переданы короч.
Судя по вопросу — вы новчиек в программировании. Поэтому — сначала научитесь программировать, а потом суйтесь в юнити.
-
Показать ещё
Загружается…
09 февр. 2023, в 15:56
20000 руб./за проект
09 февр. 2023, в 15:55
75000 руб./за проект
09 февр. 2023, в 15:13
2000 руб./за проект
Минуточку внимания
Здравствуйте. Такая проблема. Написала код, но программа выдает «System.Console» не содержит определение для «Writeline» (CS0117). Помогите, пожалуйста, исправить.
/* * Created by SharpDevelop. * User: Home * Date: 22.03.2015 * Time: 12:58 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace капит { class Invesment { public static void Main(){ int i; decimal amount, rate, profit, profit_i, win; amount = 15000.0m; rate = 0.15m; profit_i = 0; profit = amount/24*rate; Console.Writeline("Прибыль за первый месяц:" + profit); for (i=0; i<24; i++) {profit_i = profit_i + amount/24 * rate; amount = amount + profit_i; Console.WriteLine("Месяц:"+ (i+1) + "Прибыль за i-й месяц:" + profit_i + "Общая сумма:" + amount); if (i == 23) { win = profit_i - profit; Console.WriteLine("Выигрыш от капитализации:" + win); } } } } }
Содержание
- Как исправить ошибки CS0117 и CS0122?
- Ошибка CS0117 в Unity.
- Ошибка CS0117 в Unity.
Как исправить ошибки CS0117 и CS0122?
По туториалу собираю Tower Defence на Unity для себя и на моменте создания скрипта для башен получаю ошибки CS0117 и CS0122.
Туториал супер наглядный, там просто пишется код и дополнительно объясняется что к чему.
По итогу его написания у человека все работает, у меня ошибки.
Дословно выглядят они так:
1) AssetsScriptsTower.cs(26,41): error CS0117: ‘Enemies’ does not contain a definition for ‘enemies’
2) AssetsScriptsTower.cs(51,21): error CS0122: ‘Enemy.takeDamage(float)’ is inaccessible due to its protection level
- Вопрос задан 13 мая 2022
- 166 просмотров
Простой 1 комментарий
1 — у тебя в классе Enemies нет члена enemies. Возможно его нет совсем, а возможно у тебя опечатка.
2 — у тебя в классе Enemy есть метод takeDamage, но он не публичный
PS: На будущее:
— отмечай комментарием, на какой именно строке сработала ошибка
— не забывай заворачивать код в тег — это сильно упростит чтение для тех, кто попробует решить твой вопрос
— перед тем как задавать вопрос — попробуй загуглить в чём суть ошибки, и попробуй сам решить (CS0117, CS0122)
— перед тем как начинать писать на юнити, лучше всё-таки хоть самые основы C# изучить. Тут как в математике — без понимания простых вещей, ты гарантированно не сможешь понять сложные вещи.
Источник
Ошибка CS0117 в Unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class движение : MonoBehaviour
<
public float speed;
public float jumpForce;
public float moveInput;
public Joystick joystick;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
private void Start()
<
rb = GetComponent ();
>
private void FixedUpdate()
<
moveInput = joystick.Horizontal;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if(facingRight == false && moveInput > 0)
<
Flip();
>
else if(facingRight == true && moveInput = .5f)
<
rb.velocity = Vector2.up * jumpForce;
>
>
void OnCollisionEnter2D(Collision2D shit)
<
if (shit.gameObject.tag == «враг»)
<
ReloadFuckingLevel ();
>
>
void ReloadFuckingLevel()
<
Application.LoadLevel (Application.loadLevel); //здесь ошибка
>
void Flip()
<
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
>
>
cs(63,44): error CS0117: ‘Application’ does not contain a definition for ‘loadLevel’ это целиком ошибка. Помогите пожалуйста.
Источник
Ошибка CS0117 в Unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class движение : MonoBehaviour
<
public float speed;
public float jumpForce;
public float moveInput;
public Joystick joystick;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
private void Start()
<
rb = GetComponent ();
>
private void FixedUpdate()
<
moveInput = joystick.Horizontal;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if(facingRight == false && moveInput > 0)
<
Flip();
>
else if(facingRight == true && moveInput = .5f)
<
rb.velocity = Vector2.up * jumpForce;
>
>
void OnCollisionEnter2D(Collision2D shit)
<
if (shit.gameObject.tag == «враг»)
<
ReloadFuckingLevel ();
>
>
void ReloadFuckingLevel()
<
Application.LoadLevel (Application.loadLevel); //здесь ошибка
>
void Flip()
<
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
>
>
cs(63,44): error CS0117: ‘Application’ does not contain a definition for ‘loadLevel’ это целиком ошибка. Помогите пожалуйста.
Источник
C# Compiler Error
CS0117 – ‘type’ does not contain a definition for ‘identifier’
Reason for the Error
This error can be seen when you are trying to reference an identifier that does not exist for that type. An example of this when you are trying to access a member using base. where the identifier doesnot exist in the base class.
For example, the below C# code snippet results with the CS0117 error because the the identifier Field1 is accesses using base.Field1 but it doesnot exist in the base class “Class1”.
namespace DeveloperPublishNamespace { public class Class1 { } public class Class2 : Class1 { public Class2() { base.Field1 = 1; } } public class DeveloperPublish { public static void Main() { } } }
Error CS0117 ‘Class1’ does not contain a definition for ‘Field1’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 11 Active
Solution
To fix the error code CS0117, remove the references that you are trying to make which is not defined in the base class.
I am attempting to dynamically compile code and execute it in runtime. So I followed http://www.tugberkugurlu.com/archive/compiling-c-sharp-code-into-memory-and-executing-it-with-roslyn as a guide.
The code given in the example works prefectly. However, if I use Console.ReadKey()
it gives me error CS0117: 'Console' does not contain a definition for 'ReadKey'
. I read somewhere that this is because dotnet core does not support ReadKey
(‘Console’ does not contain a definition for ‘ReadKey’ in asp.net 5 console App), but I am currently using "Microsoft.NETCore.App"
and it Console.ReadKey()
works perfectly if I use it explicitly in code instead of while using Roslyn.
- Is this an issue with Roslyn or am I doing something wrong?
- Are
"Microsoft.NETCore.App"
anddotnet core
the same thing? I suspect I might be using something else as my target (which allows me to useReadKey
) and dotnet core with Roslyn - Is it possible to change Roslyn’s target to something else?
Thanks in advance.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
namespace DemoCompiler
{
class Program
{
public static void roslynCompile()
{
string code = @"
using System;
using System.Text;
namespace RoslynCompileSample
{
public class Writer
{
public void Write(string message)
{
Console.WriteLine(message);
Console.ReadKey();
}
}
}";
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
string assemblyName = Path.GetRandomFileName();
MetadataReference[] references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location)
};
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
else
{
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
var type= assembly.GetType("RoslynCompileSample.Writer");
var instance = assembly.CreateInstance("RoslynCompileSample.Writer");
var meth = type.GetMember("Write").First() as MethodInfo;
meth.Invoke(instance, new [] {assemblyName});
}
}
}
}
}
Edit : I tried to reference System.Console.dll
but I got conflict between that and System.Private.CoreLib
. How do I resolve it?
asked Mar 13, 2017 at 13:42
4
One approach would be to add <PreserveCompilationContext>true</PreserveCompilationContext>
* to your project file and then use Microsoft.Extensions.DependencyModel.DependencyContext
to get all reference assemblies for current project:
var references = DependencyContext.Default.CompileLibraries
.SelectMany(l => l.ResolveReferencePaths())
.Select(l => MetadataReference.CreateFromFile(l));
This seems to avoid the errors you get, but causes warnings like:
warning CS1701: Assuming assembly reference ‘System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ used by ‘System.Console’ matches identity ‘System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ of ‘System.Runtime’, you may need to supply runtime policy
As far as I can tell, this should not be an issue.
* This assume you’re using csproj/VS2017. If you’re still on project.json/VS2015, the same can be done using "buildOptions": { "preserveCompilationContext": true }
.
answered Mar 13, 2017 at 22:10
svicksvick
232k50 gold badges385 silver badges509 bronze badges
2
Found a similar issue at https://github.com/dotnet/roslyn/issues/13267 with the solution.
I have got around this (as far as I can tell) by:
Copying
System.Runtime.dll
andSystem.Runtime.Extensions.dll
from:
C:Users<user>.nugetpackagesSystem.Runtime4.1.0refnetstandard1.5
and putting them in a References folder in my project. So then instead of referencingmscorlib.dll
andSystem.Private.CoreLib.dll
I reference these
I tried this and found referencing only System.Runtime.dll
is sufficient (at least in my case). Just to be clear, instead of MetadataReference.CreateFromFile(typeof(Object).GetTypeInfo().Assembly.Location)
, I now use MetadataReference.CreateFromFile("System.Runtime.dll")
which refers to the DLL present in the working directory directly.
The only downside being I’ll have to distribute the dll along with my project but that is okay considering I can now use Roslyn properly on .net core instead of changing the base framework to full .net
answered Mar 16, 2017 at 18:55
GrimsonGrimson
5381 gold badge5 silver badges18 bronze badges