I Have this error but i can’t identify the error (CS0542) for some reason:
member names cannot be the same as their enclosing type
Code:
class SuperTeam
{
string SuperTeamName;
public SuperTeam()
{
SuperTeamName = "";
}
public void SuperTeam (string nSuperTeamName)
{
SuperTeamName = nSuperTeamName;
}
}
asked Dec 4, 2013 at 21:52
6
The problem is here:
public void SuperTeam(string nSuperTeamName)
{
SuperTeamName = nSuperTeamName;
}
I believe you wanted to have a constructor for your class, and since constructor can’t have a return type, the compiler is treating it as a method. Now the method name is same as the class name, that is why you are getting the error.
- If it is a constructor then remove
void
(return type) - If it is a simple method then change the name to something other than
SuperTeam
See Details about your Error — Compiler Error CS0542:
The members of a class or struct cannot have the same name as the
class or struct, unless the member is a constructor
AND (thanks to @Alexei Levenkov)
This error might be caused if you inadvertently put a return type on
a constructor, which in effect makes it into an ordinary method.
answered Dec 4, 2013 at 21:56
HabibHabib
217k28 gold badges402 silver badges429 bronze badges
2
Your class is SuperTeam and it has a method called SuperTeam that isn’t a constructor. I’m guessing that it was supposed to be a constructor, in which case, drop the void
return type
public SuperTeam (string nSuperTeamName)
{
SuperTeamName = nSuperTeamName;
}
If it’s actually supposed to be a method for setting SuperTeamName
then change the name of the function (SetSuperTeamName
would seem appropriate), or better yet change it into a property with a getter and a setter.
answered Dec 4, 2013 at 21:55
Matt BurlandMatt Burland
44.2k18 gold badges95 silver badges168 bronze badges
you have conflict the method has some name as the class constructor
try this for example
public SuperTeam()
{
SuperTeamName = "";
}
public void SuperTeamMethod (string nSuperTeamName)
{
SuperTeamName = nSuperTeamName;
}
answered Dec 4, 2013 at 21:54
BRAHIM KamelBRAHIM Kamel
13.3k34 silver badges46 bronze badges
Your constructor with the string nSuperTeamName
is not supposed to have void
. By having void
, you made it one of the class’ members.
answered Dec 4, 2013 at 21:54
error CS0542
пытался сделать оптимизацию путём отключения рендера объекта когда на него не смотрит камера, и включения обратно когда камера смотрит
получилось вот так
Используется csharp
using UnityEngine;
using System.Collections;
public class OnBecameVisible : MonoBehaviour {
void OnBecameInvisible() {
gameObject.GetComponent<MeshRenderer>().enabled = false;
}
void OnBecameVisible() {
gameObject.GetComponent<MeshRenderer>().enabled = false;
}
}
но Юнька выдаёт ошибку
error CS0542: `OnBecameVisible.OnBecameVisible()’: member names cannot be the same as their enclosing type
Последний раз редактировалось waruiyume 04 май 2015, 23:44, всего редактировалось 1 раз.
Причина: Переименовано
- Andrey_Sop
- UNец
- Сообщения: 13
- Зарегистрирован: 31 мар 2015, 22:29
Re: Оптимизация и помощь в скрипте
waruiyume 04 май 2015, 23:43
Переводить ошибку не пробовали?
Никакого профита от такой оптимизации не будет.
-
waruiyume - Адепт
- Сообщения: 6061
- Зарегистрирован: 30 окт 2010, 05:03
- Откуда: Ростов на Дону
Re: error CS0542
getAlex 05 май 2015, 14:39
1) Рендер и так отключается когда камера его не видит.
Frustum Culling отрезает весь рендер, не входящий в плоскости камеры(по умолчанию существует и всегда активен), а Occlusion Culling отрезает всё что не видит камера (если одни объекты заслоняют другие) — по умолчанию включен, выглядит как bool переменная на камере.
2) Функции не могут быть с таким же именем, как и название класса(Не считая перегрузку функций, но у них разная сигнатура, а у вас одна). Есть такая штука, называется конструктор класса. Вот у конструктора имя
может быть
должно быть такое же, как и у класса
- getAlex
- Адепт
- Сообщения: 1775
- Зарегистрирован: 10 авг 2013, 18:30
Вернуться в Скрипты
Кто сейчас на конференции
Сейчас этот форум просматривают: Google [Bot] и гости: 5
- Remove From My Forums
-
Question
-
Normally if I use a field whose name is also the name of a class, then this error — «Member names cannot be the same as their enclosing type.» — is thrown. However, when using the PhysX.Net bindings (x64), I can do this.
using PhysX; public class Example { public Example Example { get; set; } // throws error public Scene Scene { get; set; } // uses PhysX, does not throw error }
Answers
-
Hi Tristan,
the member-name cannot be the class-name that contains that member. But the member-name can be the same as the return-type (what you have with the Scene).
So this does not work:
public class Example { public Example Example { get; set; } // throws error }
The reason is that the member «Example» is already reserved for the constructor. So you can’t define any other member with that name.
But what works is the following:
public class Example { } public class AnotherClass { public Example Example { get; set; } }
Now the Example-Property is in a class called «AnotherClass». So the member-name is different from the type that contains it. Works fine.
And when you look now at your working «Scene»-property, this only works because it’s not in a class called «Scene», but in a class called «Example». It has nothing to do with PhysX.
-
Proposed as answer by
Wednesday, September 9, 2015 7:33 AM
-
Marked as answer by
Herro wongMicrosoft contingent staff
Tuesday, September 15, 2015 7:10 AM
-
Proposed as answer by
-
Example is a property of type Example, in the class («enclosing type») Example.
This error has nothign to do with the type and the Property name being the same. For example, this would also give you the same compile time exception:
public class Example { public string Example { get; set; } }
If the property/field has the same name as the class, the compiler would be unable to know if you mean the field/property or the class in any given context.
//This could be the start of either accessing some static method, or the property. Wich of those two is it? Example
-
Proposed as answer by
Herro wongMicrosoft contingent staff
Wednesday, September 9, 2015 7:33 AM -
Marked as answer by
Herro wongMicrosoft contingent staff
Tuesday, September 15, 2015 7:10 AM
-
Proposed as answer by